MVC 6 绑定属性消失了吗?
MVC 6 Bind Attribute disappears?
请原谅我的菜鸟问题,但我注意到绑定属性不再作为 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 的视图,它仅以 readonly/display 形式显示 UserName
,在可编辑字段中显示 FirstName
和 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");
}
请原谅我的菜鸟问题,但我注意到绑定属性不再作为 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 的视图,它仅以 readonly/display 形式显示 UserName
,在可编辑字段中显示 FirstName
和 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");
}