【问题标题】:MVC 6 Bind Attribute disappears?MVC 6 绑定属性消失?
【发布时间】:2015-12-14 05:28:22
【问题描述】:

请原谅我的菜鸟问题,但我注意到绑定属性在 MVC 6 的控制器模板中不再显示为默认值。

我知道该属性仍然存在,但我们还需要使用它们吗?我听说它们可以用来防止过度发布攻击。他们是否将其删除是因为 MVC 6 可以在不使用它们的情况下找出防止这种情况的方法?还是有更安全的方法来防止这种情况发生?

【问题讨论】:

    标签: security asp.net-core-mvc


    【解决方案1】:

    防止过度发布的最佳方法是获取实体,仅更新需要更新的属性并保存。

    假设你有一个类似的视图模型

    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,在可编辑字段中显示 FirstNameLastName。因此,即使用户通过某种方式发布了更新的 UserName,我们也不应该更新该字段值。

    [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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多