Thursday, July 19, 2012

Protect mass assignment for ASP.NET MVC

In Ruby on Rails, we should protect mass assignment with defining attr_protected (black list) or attr_accessible (white list) on Model like this (via Ruby on Rails Guides).

(black list)
class SomeModel
  attr_protected :admin
  ...
end
(white list)
class SomeModel
  attr_accessible :name
  ...
end

I learned from the book Programming Microsoft® ASP.NET MVC, Second Edition that we should protect mass assignment with defining attribute on argument of Action method, not on Model directly.

(black list)
[HttpPost]
public ActionResult Create([Bind(Exclude="admin")]SomeModel model)
{
    ...
}
(white list)
[HttpPost]
public ActionResult Create([Bind(Include="name")]SomeModel model)
{
    ...
}

The best advantage of this approach is to be able to define black lists or white lists in each actions.

No comments:

Post a Comment