This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

ASP.NET Web API-Routing


Routing, as you may know, is a pattern matching mechanism that evaluates incoming requests and determines what to do with them. The first match in an Order's comparison of a URL pattern to the routes patterns listed in the Route dictionary wins. This implies that the controller and action supplied in the URL will be executed by the first route that successfully matches a controller, action, or action parameter.

You can do routing in three types in ASP.NET Web API.

  1. Global Level Routing
  2. Controller Level Routing
  3. Action Level Routing

1. Global Level Routing

This is the by default routing in asp.net Web API project. Web API by default use the URI "DomainName/api/ControllerName/Id" with Id as an optional argument. The routing code in the register Method in the WebApiConfig.cs file under the App_Start folder must be changed if we want to change the routing globally.

We defined this route in the Web.Config.cs file.

ASP.NET web API Routing

The default route pattern for a Web API Project is defined as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPIStart
{
    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 }
            );
        }
    }
}

As shown in the above code we can change the routeTemplate value as per our requirement. If we want routing with action name then we have to change our routeTemplate as below.

routeTemplate: "api/{controller}/{action}/{id}"

In the above code our URI is changed as.

DomainName/api/ControllerName/ActionName/Id

We can also change the constant keyword api and can give any name but for differentiating between MVC controller and web API controller we are using starting as api Keyword.

In the WebApiConfig.cs page, we may globally define different routes according to our needs, but the order is important.

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

The request will execute the Get() action method of the ValuesController because the HTTP method is GET and the URL is http://localhost:xxxx/api/values, which matches the DefaultApi route template /api/controller/id where the value of controller will be ValuesController. This is because the DefaultApi route is configured in the WebApiConfig class mentioned above. If there is no id present in the url, the id argument will be disregarded because the default route specifies that it is an optional parameter. The ValueController's Get() action method will be called because the request's HTTP method is GET.

The Web API framework will respond with a 404 error message if it cannot match a request with any available routes.

We can understand very easily what is the flow of the route in Web API. The Web API Routing is shown in the following figure.

ASP.NET web API Routing
ASP.NET web API Routing

2. Controller Level Routing

You can define routing on controller level. In ASP.NET Web API, controller level routing allows you to define custom routes for individual controllers or groups of controllers. This feature gives you more control over the URL structure and allows you to create meaningful and descriptive routes for your API endpoints.

Often, the routes in a controller all start with the same prefix.

Example

public class BooksController : ApiController
{
    [Route("api/books")]
    public IEnumerable GetBooks() { ... }

    [Route("api/books/{id:int}")]
    public Book GetBook(int id) { ... }

    [Route("api/books")]
    [HttpPost]
    public HttpResponseMessage CreateBook(Book book) { ... }
}

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.

[RoutePrefix("api/ Users")]
public class  UsersController : ApiController
{
    [HttpGet]
    [Route("")]
    public IHttpActionResult GetAll Users()
    {
        // Logic to retrieve all  Users
    }

    [HttpGet]
    [Route("{id}")]
    public IHttpActionResult Get UserById(int id)
    {
        // Logic to retrieve a  User by ID
    }

    [HttpPost]
    [Route("")]
    public IHttpActionResult Create User( User  User)
    {
        // Logic to create a new  User
    }

    [HttpPut]
    [Route("{id}")]
    public IHttpActionResult Update User(int id,  User  User)
    {
        // Logic to update a  User
    }

    [HttpDelete]
    [Route("{id}")]
    public IHttpActionResult Delete User(int id)
    {
        // Logic to delete a  User
    }
}

The [Route] attribute is then used to define the specific routes for each action. With this setup, the following routes will be available:

  • GET: /api/ Users - Retrieves all  Users
  • GET: /api/ Users/{id} - Retrieves a  User by ID
  • POST: /api/ Users - Creates a new  User
  • PUT: /api/ Users/{id} - Updates a  User by ID
  • DELETE: /api/ Users/{id} - Deletes a  User by ID

3. Action Level Routing

To implement action level routing in ASP.NET Web API, you can use the [Route] attribute directly on the action methods within your controller.

Here's an example.

public class UsersController : ApiController
{
    [HttpGet]
    [Route("api/Users")]
    public IHttpActionResult GetAllUsers()
    {
        // Logic to retrieve all Users
    }

    [HttpGet]
    [Route("api/User/{id}")]
    public IHttpActionResult GetUserById(int id)
    {
        // Logic to retrieve a User by ID
    }

    [HttpPost]
    [Route("api/User")]
    public IHttpActionResult CreateUser(User user)
    {
        // Logic to create a new User
    }

    [HttpPut]
    [Route("api/Users/{id}")]
    public IHttpActionResult UpdateUser(int id, User user)
    {
        // Logic to update a User
    }

    [HttpDelete]
    [Route("api/User/{id}")]
    public IHttpActionResult DeleteUser(int id)
    {
        // Logic to delete a User
    }
}

The [Route] attribute is used directly on each action method to define its specific route.

With this setup, the following routes will be available.

  • GET: /api/Users- Retrieves all Users
  • GET: /api/User/{id} - Retrieves a User by ID
  • POST: /api/User - Creates a new User
  • PUT: /api/User/{id} - Updates a User by ID
  • DELETE: /api/User/{id} - Deletes a User by ID

Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#