Thoughts on Software

Archive for the ‘LINQ’ Category

How to distinguish HTTP POST action methods at runtime

with one comment

I had a requirement recently to only apply an action filter to HTTP POST action methods on the controller. So the task was to create a conditional filter provider (which I will cover in a later post) which would only return the attribute if the action also had the HttpPostAttribute applied.

It turns out that it is actually quite simple to discover whether the HttpPostAttribute has been applied if you have access to an ActionDescriptor object, which you can get at from the FilterContext object available to filter attributes in their OnActionExecuting, OnActionExecuted, OnResultExecuting and OnResultExecuted methods as well as in the filter provider. Then it’s just a case of using the GetCustomAttributes and a bit of LINQ to find out if any of the action’s attributes are an HttpPostAttribute:


public static bool IsHttpPost(ActionDescriptor action)
    return action.GetCustomAttributes(typeof(HttpPostAttribute), true).Any();


Written by andrewlocatelliwoodcock

January 23, 2012 at 21:11

Accessing Model validation errors from the Controller

with 16 comments

MVC performs automatic model validation whilst it is binding the model, so as soon as we hit the Controller action method that is being called, we have access to a validated model. In fact, as discussed in my last post, we actually have access to the results of model validation in the method’s ActionFilters, including the first ActionFilter: OnActionExecuting, which fires before we even reach the action method.

MVC Exposes the results of this validation through the Controller’s ViewData.ModelState property. This is directly accessible in the Controller by calling ModelState and is most often used to check whether a model passed validation:


if (ModelState.IsValid)
    // model passed validation, so do some work here


But if ModelState.IsValid returns false, ie the model failed validation, how can we see the collection of errors?

Read the rest of this entry »

Written by andrewlocatelliwoodcock

December 16, 2011 at 20:17