The MVC framework: the AcceptVerbsAttribute class

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!


~ by Luis Abreu on February 3, 2009.

2 Responses to “The MVC framework: the AcceptVerbsAttribute class”

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

  2. Hello. can you be more specific?

Leave a Reply

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

You are commenting using your 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: