MVC 安全性:ViewModel 与 [Bind()] 注释。两者都需要,还是其中之一就足够了?
MVC Security: ViewModel vs. [Bind()] annotation. Are both needed, or is one or the other enough?
我一直在寻找这个问题的答案,因为我希望我的代码尽可能安全。
就安全性而言,ViewModel
和 [Bind()]
是否等同?
详细说明
假设您有以下型号:
Model.cs
public class Model
{
public int Id { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(20, MinimumLength = 2)]
public string Something { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(40, MinimumLength = 4)]
public string SomethingElse { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(60, MinimumLength = 8)]
public string AnotherSomethingElse { get; set; }
}
ModelController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Something([Bind(Include="Something,SomethingElse")] Model model)
{
// Do stuff here
}
在这种情况下,我使用 [Bind()]
注释从 Something(Model model)
所做的任何事情中排除其他数据。我只允许我想要的输入。
但是如果我改用 ViewModel
会怎样?像这样:
模型视图Model.cs
public class ModelViewModel
{
// Security annotations intentionally removed to keep question compact.
public string Something { get; set; }
public string SomethingElse { get; set; }
}
...我还需要在 Something(Model model)
中使用 [Bind()]
吗?在排除不需要的列进行更新时,它们是相互独立的,还是它们都以相同的方式工作?
我是不是误解了它的工作原理?
两者绝对等价,而且足够安全。不过,使用 ViewModel
似乎更自然。无需保留允许绑定的一长串属性列表。视图模型就是为了这个目的。如果您使用视图模型,则不需要任何 Bind()
属性。视图模型的属性决定了从请求中反序列化的内容。其他的都扔掉了。
我一直在寻找这个问题的答案,因为我希望我的代码尽可能安全。
就安全性而言,ViewModel
和 [Bind()]
是否等同?
详细说明
假设您有以下型号:
Model.cs
public class Model
{
public int Id { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(20, MinimumLength = 2)]
public string Something { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(40, MinimumLength = 4)]
public string SomethingElse { get; set; }
[Required]
[RegularExpression(Regex, ErrorMessage = RegexError)]
[StringLength(60, MinimumLength = 8)]
public string AnotherSomethingElse { get; set; }
}
ModelController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Something([Bind(Include="Something,SomethingElse")] Model model)
{
// Do stuff here
}
在这种情况下,我使用 [Bind()]
注释从 Something(Model model)
所做的任何事情中排除其他数据。我只允许我想要的输入。
但是如果我改用 ViewModel
会怎样?像这样:
模型视图Model.cs
public class ModelViewModel
{
// Security annotations intentionally removed to keep question compact.
public string Something { get; set; }
public string SomethingElse { get; set; }
}
...我还需要在 Something(Model model)
中使用 [Bind()]
吗?在排除不需要的列进行更新时,它们是相互独立的,还是它们都以相同的方式工作?
我是不是误解了它的工作原理?
两者绝对等价,而且足够安全。不过,使用 ViewModel
似乎更自然。无需保留允许绑定的一长串属性列表。视图模型就是为了这个目的。如果您使用视图模型,则不需要任何 Bind()
属性。视图模型的属性决定了从请求中反序列化的内容。其他的都扔掉了。