Feb 03

The AcceptVerbsAttribute was introduced in a previous release of the framework and its main objective is to let restrict an action method to certain HTTP method(s) (PUT, POST, etc). So, lets reuse the default web site that is created from the ASP.NET MVC and change the About action method default so that it can only be used through a post request. To achieve this, you only need to add the AcceptVerbsAttribute to the method:

public ActionResult About() {
    return View();

And now if you try to execute this action from a request that isn’t made through a post you’ll get a 404 error. You’ll trigger this error if you try to execute this action through the About option you’ve got on the top menu.

When you use this class, you have two options:

  • you can specify the allowed verbs though the constructor that accepts a params arrays of strings;
  • You can use the overloaded constructor which receives a value from the HttpVerbs enumeration, which, as you might expect is a flags enumeration.

As a side note, take a look at the code and check the way the HttpVerbs enumeration is implemented…yep, they’re using the left shift operator in order to shift the existing bits in 1 n bits to the left. I find this interesting because most implementations of these enumerations will only use integers (calculated by multiplying the previous value by 2). Ok, back to business…

The AcceptVerbsAttribute expands the abstract ActionMethodSelectorAttribute class which ony has one method:

public abstract bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo);

As you might expect,AcceptVerbsAttribute implements this method by recovering the HTTP method from the current request and by checking if  is is in the allowed list of verbs allowed by the current instance. And that’s it…there’s really nothing more to say about this class. You’re probably wondering on how this class is used by the runtime,but we’ll leave that for a future post. Keep tuned!

2 comments so far

  1. Spencer
    3:23 pm - 2-10-2009

    Can you show me how the posted data to be within action method.

  2. luisabreu
    6:54 pm - 2-10-2009

    Hello. can you be more specific?