MVC 6 Bind Attribute disappears?

2019-01-05 06:04发布

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.

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?

1条回答
We Are One
2楼-- · 2019-01-05 06:43

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;}

}

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");
}
查看更多
登录 后发表回答