Thursday, August 8, 2019

Routing in WebAPI?

Routing is how Web API matches a URI to an action.


It routes an incoming HTTP request to a particular action method on a Web API controller.


Web API supports two types of routing:
  1. Convention-based Routing
  2. Attribute Routing

Convention-based Routing

In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.

Example:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable attribute routing
        config.MapHttpAttributeRoutes();
        
        // Add default route using convention-based routing
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}


Configure Multiple Routes

However, you can configure multiple routes in the Web API using HttpConfiguration object.


Attribute Routing

Attribute routing is supported in Web API 2. As the name implies, attribute routing uses [Route()] attribute to define routes. The Route attribute can be applied on any controller or action method.
In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config.MapHttpAttributeRoutes() method.

Example:
public class StudentController : ApiController
{
    [Route("api/student/names")]
                public IEnumerable<string> Get()
    {
                return new string[] { "student1", "student2" };
    }
}


No comments:

Post a Comment

Web API Versioning.

 Implement the new feature without impacting the existing consumers we can solve this problem by API versioning. When the business has start...