Maarten Balliauw {blog}

ASP.NET MVC, Microsoft Azure, PHP, web development ...

NAVIGATION - SEARCH

ASP.NET MVC preview 5's AntiForgeryToken helper method and attribute

The new ASP.NET MVC preview 5 featured a number of new HtmlHelper methods. One of these methods is the HtmlHelper.AntiForgeryToken. When you place <%=Html.AntiForgeryToken()%> on your view, this will be rendered similar to the following:

[code:c#]

<input name="__MVC_AntiForgeryToken" type="hidden" value="Ak8uFC1MQcl2DXfJyOM4DDL0zvqc93fTJd+tYxaBN6aIGvwOzL8MA6TDWTj1rRTq" />

[/code]

When using this in conjunction with the action filter attribute [ValidateAntiForgeryToken], each round trip to the server will be validated based on this token.

[code:c#]

[ValidateAntiForgeryToken]
public ActionResult Update(int? id, string name, string email) {
    // ...
}

[/code]

Whenever someone tampers with this hidden HTML field's data or posts to the action method from another rendered view instance, this ValidateAntiForgeryToken will throw a AntiForgeryTokenValidationException.

kick it on DotNetKicks.com

Using the ASP.NET MVC ModelBinder attribute

ASP.NET MVC action methods can be developed using regular method parameters. In earlier versions of the ASP.NET MVC framework, these parameters were all simple types like integers, strings, booleans, … When required, a method parameter can be a complex type like a Contact with Name, Email and Message properties. It is, however, required to add a ModelBinder attribute in this case.

Here’s how a controller action method could look like:

[code:c#]

public ActionResult Contact([ModelBinder(typeof(ContactBinder))]Contact contact)
{
    // Add data to view
    ViewData["name"] = contact.Name;
    ViewData["email"] = contact.Email;
    ViewData["message"] = contact.Message;
    ViewData["title"] = "Succes!";

    // Done!
    return View();
}

[/code]

Notice the ModelBinder attribute on the action method’s contact parameter. It also references the ContactBinder type, which is an implementation of IModelBinder that also has to be created in order to allow complex parameters:

[code:c#]

public class ContactBinder : IModelBinder
{
    #region IModelBinder Members

    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        if (modelType == typeof(Contact))
        {
            return new Contact
            {
                Name = controllerContext.HttpContext.Request.Form["name"] ?? "",
                Email = controllerContext.HttpContext.Request.Form["email"] ?? "",
                Message = controllerContext.HttpContext.Request.Form["message"] ?? ""
            };
        }

        return null;
    }

    #endregion
}

[/code]

UPDATE: Also check Timothy's blog post on this one.
UPDATE: And my follow-up blog post.

kick it on DotNetKicks.com