ASP.NET MVC: AcceptVerbsAttribute and ActionMethodSelectorAttribute

Earlier I mentioned the ActionNameAttribute that allows one to rename the action a controller method responds to in the ASP.NET MVC Framework. I also mentioned the NonActionAttribute in the MVC Framework which makes sure a controller method does not respond to an action request. All of this is part of the internal operations of the ActionMethodSelector Class for mapping a request to an actual controller method.


 


AcceptVerbsAttribute and ActionMethodSelectorAttribute


In addition to the ActionNameSelectorAttribute which queries for a valid name, there is also an ActionMethodSelectorAttribute that queries to see if a method can handle a request given the current ControllerContext:


 



public abstract class ActionMethodSelectorAttribute : Attribute {


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


}


 


One of the most used derivatives of the ActionMethodSelectorAttribute is the AcceptVerbsAttribute that allows one to specify if an action should respond to only a HTTP GET, POST, etc. request:


 



// Example of Using AcceptVerbs


[ActionName(“Delete”), AcceptVerbs(HttpVerbs.Post)]


public ActionResult Remove(int id)


 


The AcceptVerbsAttribute just checks to see if the incoming HttpMethod for the current request is in the list of verbs provided in the attribute:


 



public override bool IsValidForRequest(ControllerContext controllerContext,


                                            MethodInfo methodInfo) {


    if (controllerContext == null) {


        throw new ArgumentNullException(“controllerContext”);


    }


 


    string incomingVerb = controllerContext.HttpContext.Request.HttpMethod;


    return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase);


}


 


So once the ActionMethodSelector Class finishes compiling a list of controller actions that can respond to an action by name, it then filters those actions via the ActionMethodSelectorAttribute. This is the second phase of a two phase process that decides which action on the controller should respond to an incoming request.


 


Conclusion


It is important to understand how the MVC Framework chooses an appropriate action to handle a request. The ActionNameSelectorAttribute and ActionMethodSelectorAttribute play an important role in the selection of a proper controller action.


 


David Hayden


 


Recent Posts:



 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>