Theme-Logo
  •   .Net
    •   C Sharp(C#)
    •   Web API
    •   Micro Services
    •   ASP.Net
    • ASP.Net MVC
    • .Net Core
  •   Database
    • SQL Server
    • Oracle
    • PostgreSQL
  •   jQuery
    • jQuery Tutorials
    • jQuery Plugins
    • jQuery UI
    • More on jquery
  •   Tutorials
    • Microservices Tutorials
    • DotNet Core Tutorials
    • PostgreSql Tutorials

Web API Routing

ASP.NET introduced Routing to eliminate the needs of mapping each URL with a physical file. Routing enables us to define a URL pattern that maps to the request handler. This request handler can be a file or class. In ASP.NET Webform application, request handler is .aspx file, and in MVC Web API, it is the Controller class and Action method.

Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.

Web API supports two types of routings. Let's discussed each one by one

1. 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.

dotnetpalace.com

When we create a Web API Project, then by default, inside App_Start folder, WebApiConfig class is added. WebApiConfig class in the App_Start folder with default route as shown below.

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

The config.Routes is a route table or route collection of type HttpRouteCollection. The "DefaultApi" route is added in the route table using MapHttpRoute() extension method. The MapHttpRoute() extension method internally creates a new instance of IHttpRoute and adds it to an HttpRouteCollection.

We can also add configure multiple routes in the Web API using HttpConfiguration object routing. See below code:

                                        public static class WebApiConfig
                                        {
                                                public static void Register(HttpConfiguration config)
                                                {
                                                    config.MapHttpAttributeRoutes();
    
                                                    // tutorials route of dotnet palace
                                                    config.Routes.MapHttpRoute(
                                                    name: "tutorials",
                                                    routeTemplate: "api/dotnetpalace/{id}",
                                                    defaults: new { controller="tutorials", id = RouteParameter.Optional }
                                                    constraints: new { id ="/d+" }
                                                    );

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

2. 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.

public class TutorialsController : ApiController
{
    [Route("api/tutorials/webapi")]
                public IEnumerable GetTutorialList()
    {
                return new string[] { "t1", "t2" };
    }
}

In the above example, the Route attribute defines new route "api/tutorials/webapi" which will be handled by the Get() action method of TutorialsController. Thus, an HTTP GET request http://localhost:1234/api/tutorials/webapi will return list of tutorials.

Non-Actions

To prevent a method from getting invoked as an action, use the [NonAction] attribute. This signals to the framework that the method is not an action, even if it would otherwise match the routing rules.

// Not an action method.
[NonAction]  
public string GetPrivateData() { ... }

Summary

To summarize, routes are an incoming HTTP request to a particular action method on a Web API controller. Hope you picked up a thing or two.

Cheers!

❮ Previous
Next ❯

Trending Post
Dependency Injection in C#
Inversion of controls (IoC)
Design patterns
Service-Oriented Architecture(SOA)
Interview Questions and Answers
What is Request delegate?
What is Host in ASP.NET Core?
Describe the Generic Host and Web Host?
Describe the Servers in ASP.NET Core?
How to read values from Appsettings.json file?
How to handle errors in ASP.NET Core?
About us

DotNet Palace is a community platform created and maintained by The articles are mainly focused on Microsoft stack technologies like C#, ASP.Net, MVC, .Net Core, SQL Server and Oracle, PostgreSQL, SQLite etc. To improve the site's content you can send your valuable suggestions at info.dotnetpalace@gmail.com

Quick links
  • SOLID Principles
  • Questions
  • OOPS Principles
  • DotNet Palace Tutorials
  • Privacy Policy
  • Terms and Condition