Monday, 31 December 2018

How ASP.NET Web API routes HTTP requests to controllers?

Create a Web API Project. You will find WebAPIConfig.cs file in App_Start folder. In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods. When the Web API framework receives a request, it routes the request to an action.
To determine which action to invoke, the framework uses a routing table. The Visual Studio project template for Web API creates a default route. This route is defined in the WebApiConfig.cs file.
When the Web API receives an HTTP request, it tries to match the URI against one of the route templates in the routing table. If no route matches, the client sends a 404 error. Once a matching route is found, Web API selects the controller and the controller action method.
To find the action, Web API looks at the HTTP verb and then looks for an action whose name begins with that HTTP verb name. For example, with a GET request, Web API looks for an action prefixed with "Get", such as "GetEmployee" or "GetAllEmployee". This is only applicable for GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH verbs. 

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 }            );        }    }


No comments:

Post a Comment