Routing in ASP.Net Web API

In the previous blog, you have seen How to create secure Web API? If you are new to Web API, please read my earlier blogs on Web API. In this blog, we will see about Routing system in ASP.Net Web API.

What is Routing?

Routing is the process which decides which action and which controller should be called.

Convention-based Routing

Once you create a Web API project in Visual Studio, you will find a file called WebApiConfig.cs
This file contains the basic routing or convention routing code like this-

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


In above code, you can see a method with name MapHttpRoute. This method has 3 parameters-
1. Route name i.e. DefaultApi
2. Route template
3. Default value. In above case, default parameter is id (You do not need to pass it with URI as it is optional.)

Let's assume that you have routing available as per above code and you have a Controller name Get
Then below URI could be there to make a request.

/api/Get - Get all records
/api/Get/1 - Get record where id is 1


Consider below Route details-

config.Routes.MapHttpRoute(
                name: "CustomApi",
                routeTemplate: "api/{controller}/{category}/{productname}",
                defaults: new { id = RouteParameter.Optional }
                );

In above scenario, Request URI can be like this -

/api/Get/Category1/product1
/api/Get/Category2/product1
/api/Get/Category3/product2
/api/Get/Category1/product2

Attribute Routing

Web API 2 onwards apart from convention routing you may use Attribute routing.
In below code route defined using attribute.

[Route("products/{pid}/product")]
        public string Get()
        {
            return "Product Details";
        }

You may define default controller as well through Routing.

  config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { controller = "order", id = RouteParameter.Optional }
            );

Hope you like this blog.

Prev Blog- What are Idempotent and Non-Idempotent methods?
Next Blog- Web API Security

Keep following SharePointCafe.Net

Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers