请原谅我的菜鸟问题,但我注意到绑定属性在 MVC 6 的控制器模板中不再显示为默认值.
Pardon me for my noob question but I notice that the bind attribute does not appears as default in controller template anymore for MVC 6.
我知道该属性仍然存在,但我们还需要使用它们吗?我听说它们可以用来防止过度发布攻击.他们是否将其删除是因为 MVC 6 可以在不使用它们的情况下找出防止这种情况的方法?还是有更安全的方法来防止这种情况发生?
I know I that the attribute is still present but do we still need to use them? I heard they can be use to prevent over-posting attack. Do they remove it because MVC 6 can figure out the way to prevent this without using them? Or is there a more secure way to prevent that?
推荐答案防止过度发布的最好方法是获取实体,只更新需要更新的属性并保存.
The best way to prevent overposting is to get the entity, update only the properties needed to update and save it.
假设你有一个类似的视图模型
Assuming you have a view model like
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 和 LastName.因此,即使用户通过某种方式发布了更新的 UserName,我们也不应该更新该字段值.
And assume there is a view called Update which shows UserName in readonly/display only form and FirstName and LastName in editable fields. So even if user posts an updated UserName via some means, we should not be updating that field value.
[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 绑定属性消失?
发布评论