请原谅我的菜鸟问题,但我注意到 MVC 6 的绑定属性不再作为默认值出现在控制器模板中。
我知道该属性仍然存在,但我们仍然需要使用它们吗?我听说它们可以用来防止过度发布攻击。他们是否会删除它,因为 MVC 6 可以找到在不使用它们的情况下防止这种情况的方法?或者有更安全的方法来防止这种情况发生吗?
防止过度发布的最佳方法是获取实体,仅更新需要更新的属性并保存它。
假设你有一个像这样的视图模型
public class CustomerViewModel
{
public int Id {set;get;}
public String UserName {set;get;}
public String FirstName {set;get;}
public String LastName {set;get;}
}
并假设有一个名为 Update 的视图,其中显示UserName
以只读/仅显示形式和FirstName
and LastName
在可编辑字段中。因此,即使用户通过某种方式发布更新的用户名,我们也不应该更新该字段值。
[HttpPost]
public ActionResult Update(CustomerViewModel model)
{
var customer = yourDbContext.Customers.FirstOrDefault(s=>s.Id==model.Id);
if(customer!=null)
{
// Updating only fields which are supposed to be updated from the view.
customer.FirstName = model.FirstName;
customer.LastName = model.LastName;
yourDbContext.Entry(customer).State = EntityState.Modified;
yourDbContext.SaveChanges();
return RedirectToAction("UpdatedSuccessfully");
}
return View("NotFound");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)