ASP.NET Web APIs: Alternative Routing Conventions

aspnet tutorial1


Like ASP.NET MVC framework routing, you can change the default route mappings to a different pattern. This is rarely necessary, however. What is more common is the need to change the default way the Web API identifies a controller action, and Web API routing gives you several options to do this.

HTTP Method Attributes

You can explicitly bind HTTP methods to actions in the controller. This is handy if you feel the default naming conventions force you to write action methods that aren’t very self-descriptive. For instance, having a controller method named “Put” doesn’t explicitly tell you what it’s doing. Even a name like “PutBook” doesn’t really imply that a Book is being edited. Perhaps you’d rather use a name like “EditBook” or “UpdateBook.” All you have to do is explicitly bind the PUT method to that action by using an HttpMethod attribute.

This forces the routing to use the EditBook method for a PUT request that comes in for that controller.

AcceptVerbs Attribute

The AcceptVerbs attribute is used similarly to the HTTP method attributes. It is useful when you want to specify a list of methods tied to the action and/or HTTP methods besides the usual four (GET, POST, PUT, DELETE).

Action Names in the URL

Much like the ASP.NET MVC framework, you can set up Web API routing to look for an action name in the URL and use that action to process the request. This is not generally recommended as it is a step away from a truly RESTful service. You want URLs to describe a resource, not an action to perform on the resource.

However, if your routing becomes unduly complicated or you want to keep to the same patterns your developers are used to from ASP.NET MVC, you can set up a routing table to look for action names in the URL. First change the routing table in Global.asax to the following:

Then use the HTTP method attributes on your actions:

This action would fire in response to a URL such as:

ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

Philip Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Be Sociable, Share!

Leave a Reply

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