Tuesday, 23 August 2016

Getting Started with ASP.NET Web API 2 (C#) Part 3

Routing by attributes

Today we will see new built-in feature in asp.net web api 2 which lets you declare the routing rules by standard C# attributes. It started its life as a NuGet package but now it’s readily available in .NET. The attributes can be applied on the controller level as well. Examples:
You can even declare multiple routes for a single action:
Let’s see if can get the api/product/{id}/albums url to work.


Re-run the app and see if the api/product/1 URL still works. It doesn’t. The problem is that we have two methods in the Controller whose name starts with “get” and accept a parameter of type int. The routing engine doesn’t know which one to call.
Inspect the WebApiConfig.cs file. Note the following call:
This call comes before the standard…


…declaration. This will ensure that the routes defined in the attributes will take precedence: if the request URL matches one of the attribute URLs then the routing engine will not search any longer.

Add the following attribute over the GetAlbums action:

Run the app again. First check if api/product/1 works and it should. 
Now go to api/product/1/albums and you should be presented with the XML representation of the albums of product 1. 

Also, try with an invalid ID, such as api/product/0/albums. You should get a 404.0 error which tells you that the URL wasn’t found.

 This is because of the constraint we added to the attribute.


3 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete