Routing in ASP.Net Web API

In this blog, we will see about Routing system in ASP.Net Web API. Routing is one of the important section 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 the 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 an attribute.

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

You may define a 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

You may also like this – ASP.Net Web API Interview Questions and Answers

Leave a Comment

RSS
YouTube
YouTube
Instagram