David Hayden [MVP C#]

Sponsors

The Lounge

News

  • CodeBetter.Com Home

Other Links

Teas

Patterns & Practices

Florida .NET Developer

Book Reviews

Tampa ASP.NET MVC Developer Group

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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:

 


Posted Sun, Nov 23 2008 5:30 PM by David Hayden

[Advertisement]