andrewlocatelliwoodcock

Thoughts on Software

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();
}

Simples!

Written by andrewlocatelliwoodcock

January 23, 2012 at 21:11

One Response

Subscribe to comments with RSS.

  1. […] a comment » Following on from my last post, there is an alternative method for distinguishing whether we are dealing with an HTTP POST. […]

  2. What a great blog

    ronald

    February 17, 2012 at 10:09


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: