Saturday, April 25, 2020

Routing in ASP.NET Web API


Here in this article I am going to explain Routing in ASP.NET Web API.


What is Routing?
Routing is a mechanism that handle the incoming request from browser and figure out what to do with that request.

If you are familiar with MVC, you are happy to know Web API routing is very similar to MVC routing. In ASP.NET Web API, controller handles the HTTP requests and call the action method of controller.

 Types of Routing
There are 2 types of routing in Web API:
1. Convention Routing
2. Attribute Routing

Convention Routing
Web API Convention routing uses route templates to determine the appropriate controllers, actions and data to execute for incoming request. If no route is found for the incoming request, an HTTP error of 404 (Not Found) will be returned.

When we create a Web API application with Web API template, WebApiConfig class is added in App_Start folder. This file has default route which works as centralized configuration of all your routes.

Code of WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using Unity;
using WEBAPI.Models;
using WEBAPI.Interface;
using WEBAPI.Services;
namespace WEBAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
         
            // Web API routes
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

MapHttpAttributeRoutes : It used to enables the attribute routing.
config.Routes : It is route table
name : This represents the name of the route. DefaultApi is the default route.
routeTemplate : This is pattern or representation of the URL.
defaults : This represents the optional parameter.


Attribute based Routing
Attribute routing is supported by Web API 2. As the name implies, attribute routing uses attribute to define routes. We can apply the attribute routing on any controller’s action method.

Attribute routing can be implemented in 2 ways:
1. Controller level Attribute routing
2. Action level Attribute routing

Controller level Attribute routing
We can apply Controller Level Attribute routing by adding [RoutePrefix(“name”)] before controller definition. RoutePrefix specify a route prefix for all actions in a controller.

Syntax
[RoutePrefix("api/aspmantra")]

Complete code of controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPI.Models;
using WEBAPI.Interface;

namespace WEBAPI.Controllers
{
    [RoutePrefix("api/aspmantra")]
    public class HelloWorldController : ApiController
    {      
        private readonly IHello _hello;
        public HelloWorldController(IHello hello)
        {
            _hello = hello;
        }
        [HttpGet]
        public string HelloMethod()
        {           
            return _hello.HelloMethod();
        }
    }
}


Controller level Attribute routing


Action level Attribute routing
We can apply Action Level Attribute routing on specific action with in the controller. To apply Action level attribute routing need to add [Route(“RouteName”)] before the action method.

Syntax
[Route("HelloWorld")]

Complete code of controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPI.Models;
using WEBAPI.Interface;

namespace WEBAPI.Controllers
{
    [RoutePrefix("api/aspmantra")]
    public class HelloWorldController : ApiController
    {      
        private readonly IHello _hello;
        public HelloWorldController(IHello hello)
        {
            _hello = hello;
        }
        [HttpGet]
        [Route("welcome")]
        public string HelloMethod()
        {           
            return _hello.HelloMethod();
        }
    }
}


Action level Attribute routing



We can also use both Convention and Attribute based routing together in one application.





No comments:

Post a Comment