Introduction

I discussed how routing works in ASP.NET Web API 2 in my previous articles. Now we will look into Routing with an example.

If you are new to Routing, then please read my previous article on Routing in ASP.NET Web API.

Requirements

Example

Step 1: Create a Web API Project.

Create a Web Api Project

Step 2: Create a Model called Project.

Right click on Models and add a new Class.

class

And Project model is,
model

Project model

Step 3: Create a Web API's empty controller called Project Controller and create the following action methods.

Note:

Scenario 1

Just run the application as is with HttpGet and observe the things in Restclient.

Run with the following url: http://localhost:53077/ and http://localhost:53077/api and you will be redirected to 403 error page. After that use the url http://localhost:53077/api/Project and you will get the list of projects.

get the list of projects

Scenario 2

Place the Http Method as attribute above the Action Methods and change the Action Methods name.

Just run the application and observe the Routing.

If you use HttpGet method and URI as http://localhost:53077/api/project.

HttpGet

As we used HttpGet, FindAll action method of Project is called. Now routing is done based on the Http Method attribute that is placed above the action method. If we use http://localhost:53077/api/project/1, then Find Action method will be called. In this example also, the framework finds the exact route template, then selects an appropriate controller. Then framework took it's path to FindAll methods based on the HttpGet attribute.

Scenario 3

Now we will pass the value of controller in the Route and will see what happens.

controller

URI is : http://localhost:53077/api/ and HttpGet are used.

As we have mentioned the Controller value in defaults of Route, the URI directly goes to FindAll action method.

If we use http://localhost:53077/api/1, then it will show 404 as No similar Route Template is found.

The result of the http://localhost:53077/api/ is as in the following screenshot:

api

Similarly, you could give wrong URI and observe the result.

Scenario 4

Now we will observe the Routing by adding a literal value to the Route Template.

We have added the following Route in WebApi.Config

Route Template

Note: Remove or Comment Default Route

The URIs http://localhost:53077/api/ and http://localhost:53077/api/Project does not work here. The Route Template will not match with the URI as we have added literal called "DemoProject" in the Template. If you use the above URL's you will be redirected to 404.

Now use http://localhost:53077/api/DemoProject/Project, we will get a list of Projects as FindAll Action method is invoked.

code

Conclusion

In this practical lab, we observed how routing takes place in Web API. We have run this exercise based on my previous article "How Routing in ASP.NET WEB API Works". Change the Routing templates and observe how routing works in Web API.