Geeks With Blogs
Liam McLennan
HTTP methods are not often thought about when coding webforms applications. Links are GETs, buttons are POSTs and it all happens automatically. With Asp.NET MVC, and other MVC frameworks like Rails, the HTTP method used is more obvious and developers are begining to care about which they use.

The problem is that GET requests tell visitors to your site, including search engines, client-side web optimizers and other automatic tools, that it is safe to make the request. Which is a problem if your checkout button causes a GET. To quote Dave Thomas, paraphrasing Tim Berners-Lee, "Use GET requests to retrieve information from the server, and use POST requests to request a change of state on the server".

To help me correctly control which HTTP methods are used to access my controller actions I created an ActionFilterAttribute. ActionFilters provide a declarative way to access the executing context immediately prior to, and immediately following, the execution of an action. They are an excellent way to introduce aspect oriented programming to an mvc application. To use my action filter you attribute a controller action like this:

[AllowedHttpMethods(AllowedMethods= new HttpMethods[] {HttpMethods.POST})]
public void Save()
{ ... }
The code for the Action Filter inherits from ActionFilterAttribute and overrides the OnActionExecuting event.

public class AllowedHttpMethodsAttribute : ActionFilterAttribute
public HttpMethods[] AllowedMethods { get; set; }

public override void OnActionExecuting(FilterExecutingContext filterContext)
int count = AllowedMethods.Count(m => m.ToString().Equals(filterContext.HttpContext.Request.HttpMethod));
if (count == 0) throw new Exception("Invalid http method: " + filterContext.HttpContext.Request.HttpMethod);

public enum HttpMethods

By adding the AllowedHttpMethods attribute to all of my controller actions I can assure that http methods are used correctly.

I also use an action filter attribute to authorize which roles can access with actions. The technique I used is based upon the article Securing Your Controller Actions by Rob Conery. Posted on Wednesday, May 21, 2008 9:59 PM | Back to top

Copyright © Liam McLennan | Powered by: