C# 需要具有 Bind 属性的 MVC 操作方法的指南

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19490121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:07:23  来源:igfitidea点击:

Need guide line for MVC action method with Bind attribute

c#asp.net-mvcasp.net-mvc-3

提问by Thomas

I was going through a action method code and i saw one attribute was used there but i really did not understand the use. here is the code

我正在浏览一个动作方法代码,我看到那里使用了一个属性,但我真的不明白它的用途。这是代码

public ActionResult User([Bind(Include = "Username,FullName,Email")]User user)
{
   if (!ModelState.IsValid()) return View(user);

   try
   {
     user.save()
     // return the view again or redirect the user to another page
   }
   catch(Exception e)
   {
     ViewData["Message"] = e.Message;
     return View(user)
   }
}

([Bind(Include = "Username,FullName,Email")]User user)

i just do not understand the above line Bind include etc

我只是不明白上面的行绑定包括等

so please help me to understand this kind of attribute used & when people write this kind of code in mvc. it will be really good help if some one make me understand with sample small code where they will use this Bind attribute.

所以请帮助我理解人们在 mvc 中编写这种代码时使用的这种属性。如果有人通过示例小代码让我理解他们将在何处使用它,那将是非常好的帮助Bind attribute

Update:Suppose i have form from where user can enter only FirstName,LastName & Gender then my action method looks like

更新:假设我有用户只能输入名字、姓氏和性别的表单,那么我的操作方法看起来像

public ActionResult Edit(string FirstName,string LastName,string Gender)
{
    // ...
}

this will work i think. then why i should use a Bind Attribute because my above action method will works fine.

我认为这会起作用。那么为什么我应该使用绑定属性,因为我上面的操作方法可以正常工作。

采纳答案by haim770

Bindattribute lets you "fine-tune" the model-binding process of certain parameter Type, without registering a custom ModelBinderspecific to the Type.

Bind属性允许您“微调”某些参数类型的模型绑定过程,而无需注册ModelBinder特定于类型的自定义。

For example, assume your Action is expecting a Personparameter defined as follows:

例如,假设您的 Action 需要一个Person定义如下的参数:

public class Person
{
    public Person(string firstName, string lastName, Gender gender)
    {
        this.FirstName = firstName;
        this.LastName = lastName;

        if (gender == Gender.Male)
            this.FullName = "Mr. " + this.FirstName + " " + this.LastName;
        else
            this.FullName = "Mrs. " + this.FirstName + " " + this.LastName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Gender Gender { get; set; }

    // 'FullName' is a computed column:
    public string FullName { get; set; }
}

And the Action:

和行动:

public ActionResult Edit(Person person)
{
    ...
}

Now, if someone is posting the following JSON:

现在,如果有人发布以下 JSON:

{
    "FirstName":"John",
    "LastName":"Smith",
    "Gender":"Male",
    "FullName":"Mrs. John Smith"
}

Your Action will now have a personwith the wrong FullName('Mrs' instead of 'Mr').

你的 Action 现在会有一个person错误的FullName('Mrs' 而不是 'Mr')。

To avoid such behavior you can use the Bindattribute and explicitly exclude the FullNameproperty from the binding process ('Black-list'):

为避免此类行为,您可以使用该Bind属性并FullName从绑定过程(“黑名单”)中明确排除该属性:

public ActionResult Edit([Bind(Exclude="FullName")] Person person)
{
    ...
}

Alternatively, you can use Includeto ignore ('Black-list') all properties and only include ('White-list') the specified properties:

或者,您可以使用Include忽略 ('Black-list') 所有属性并仅包含 ('White-list') 指定的属性:

public ActionResult Edit([Bind(Include="FirstName,LastName,Gender")] Person person)
{
    ...
}

More info on MSDN.

有关MSDN 的更多信息。

回答by greg84

When this action is executed the MVC model binder will use the request parameters to populate the userparameter's properties, as you may already know. However, the Bindattribute tells the model binder to onlypopulate properties with names specified.

执行此操作时,MVC 模型绑定器将使用请求参数来填充user参数的属性,您可能已经知道了。但是,该Bind属性告诉模型绑定器填充具有指定名称的属性。

So in this case only the Username, FullNameand Emailproperties will be populated. All others will be ignored.

所以在这种情况下,只会填充Username,FullNameEmail属性。所有其他人都将被忽略。

See here for more details: http://ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/

有关更多详细信息,请参见此处:http: //ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/

回答by haim770

The Bind attribute is one way to protect against over-posting in create scenarios. For example, suppose the Student entity includes a Secret property that you don't want this web page to set.

Bind 属性是在创建场景中防止过度发布的一种方法。例如,假设 Student 实体包含您不希望此网页设置的 Secret 属性。

public class Student
{
  public int ID { get; set; }
  public string LastName { get; set; }
  public string FirstMidName { get; set; }
  public DateTime EnrollmentDate { get; set; }
  public string Secret { get; set; }

  public virtual ICollection<Enrollment> Enrollments { get; set; }
}

Even if you don't have a Secret field on the web page, a hacker could use a tool such as fiddler, or write some JavaScript, to post a Secret form value. Without the Bind attribute limiting the fields that the model binder uses when it creates a Student instance, the model binder would pick up that Secret form value and use it to create the Student entity instance. Then whatever value the hacker specified for the Secret form field would be updated in your database. The following image shows the fiddler tool adding the Secret field (with the value "OverPost") to the posted form values. The value "OverPost" would then be successfully added to the Secret property of the inserted row, although you never intended that the web page be able to set that property.

即使网页上没有 Secret 字段,黑客也可以使用 fiddler 等工具或编写一些 JavaScript 来发布 Secret 表单值。如果没有 Bind 属性限制模型绑定器在创建 Student 实例时使用的字段,模型绑定器将选取该 Secret 表单值并使用它来创建 Student 实体实例。然后黑客为 Secret 表单字段指定的任何值都将在您的数据库中更新。下图显示了将 Secret 字段(值为“OverPost”)添加到已发布表单值的提琴手工具。然后,值“OverPost”将成功添加到插入行的 Secret 属性中,尽管您从未希望网页能够设置该属性。

It's a security best practice to use the Include parameter with the Bind attribute to whitelist fields. It's also possible to use the Exclude parameter to blacklist fields you want to exclude. The reason Include is more secure is that when you add a new property to the entity, the new field is not automatically protected by an Exclude list.

将 Include 参数与 Bind 属性一起用于白名单字段是一种安全最佳实践。也可以使用 Exclude 参数将要排除的字段列入黑名单。Include 更安全的原因是,当您向实体添加新属性时,新字段不会自动受到 Exclude 列表的保护。