1

How to Add a Global Route Prefix in ASP.NET Core

 10 months ago
source link: https://code-maze.com/aspnetcore-add-global-route-prefix/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Add a Global Route Prefix in ASP.NET Core

Publisher Logo

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy.

How to Add a Global Route Prefix in ASP.NET Core

Posted by Code Maze | Jun 15, 2023 | 0

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we will learn how to add a global route prefix in ASP.NET Core. This enables us to effortlessly incorporate the route prefix into our application’s routing mechanism, offering greater flexibility and control.

To download the source code for this article, you can visit our GitHub repository.

By default, we define routing on a per-action basis. However, in certain scenarios, we may want to incorporate a global route prefix explicitly, applying it to all routes in our application.

To achieve this, we can leverage a middleware approach, which provides a centralized mechanism for adding the prefix.

Before diving into this topic, we recommend reading the basics of Working with ASP.NET Core Middleware.

Implement Global Route Prefix With Middleware

There are a few steps that we have to follow to achieve this using middleware in ASP.NET Core.

First, we need to create a new GlobalRoutePrefixMiddleware class to handle a global route prefix:

public class GlobalRoutePrefixMiddleware
private readonly RequestDelegate _next;
private readonly string _routePrefix;
public GlobalRoutePrefixMiddleware(RequestDelegate next, string routePrefix)
_next = next;
_routePrefix = routePrefix;
public async Task InvokeAsync(HttpContext context)
context.Request.PathBase = new PathString(_routePrefix);
await _next(context);
public class GlobalRoutePrefixMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _routePrefix;

    public GlobalRoutePrefixMiddleware(RequestDelegate next, string routePrefix)
    {
        _next = next;
        _routePrefix = routePrefix;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        context.Request.PathBase = new PathString(_routePrefix);
        await _next(context);
    }
}

The constructor accepts RequestDelegate parameter and a string parameter representing the desired global prefix. The InvokeAsync method serves as the entry point for the middleware’s execution and accepts the HttpContext. This method is responsible for modifying the PathBase property of the incoming request in order to add a global prefix.

Inside the InvokeAsync method, we set the context.Request.PathBase property to a new PathString instance, using the _routePrefix variable as its value. This means that the route prefix specified in _routePrefix will be appended to the base path of the request URL.

After setting the PathBase, the method calls the _next delegate, passing the modified context object as an argument.

Next, in our Program.cs file, let’s include the GlobalRoutePrefixMiddleware:

app.UseMiddleware<GlobalRoutePrefixMiddleware>("/api/v1");
app.UseMiddleware<GlobalRoutePrefixMiddleware>("/api/v1");

It is crucial to ensure that we place the UseMiddleware early in the pipeline, before any middleware that relies on routing.

Here we’re passing “/api/v1” as the prefix into the constructor so that the prefix will be applied to all routes in our application.

Testing the Global Route Prefix

To test this, let’s create a simple ProductsController with the GetProducts action:

namespace GlobalRoutePrefixInAspNetCore.API.Controllers
[ApiController]
[Route("products")]
public class ProductsController : ControllerBase
[HttpGet]
public ActionResult<List<Product>> GetProducts()
var products = new List<Product>()
new Product { Id = 1,Name = "The Secret Recipes of Chef Uyi",Category = "Book",Price = 100},
new Product { Id = 2,Name = "Lenovo Yoga Laptop",Category = "Tech Gadget",Price = 2000}
return Ok(products);
namespace GlobalRoutePrefixInAspNetCore.API.Controllers
{
    [ApiController]
    [Route("products")]
    public class ProductsController : ControllerBase
    {
        [HttpGet]
        public ActionResult<List<Product>> GetProducts()
        {
            var products = new List<Product>()
            {
                new Product { Id = 1,Name = "The Secret Recipes of Chef Uyi",Category = "Book",Price = 100},
                new Product { Id = 2,Name = "Lenovo Yoga Laptop",Category = "Tech Gadget",Price = 2000}
            };

            return Ok(products);
        }
    }
}

By applying the middleware approach with a global route prefix, the GetProducts action’s actual URL becomes "/api/v1/products". The “/api/v1” prefix will be automatically added to all routes defined in our application. This also helps with API versioning.

Conclusion

In this article, we learned how adding a global route prefix in ASP.NET Core is achievable using middleware. We adopted an approach that utilizes the GlobalRoutePrefixMiddleware class to add the prefix. This method enables us to achieve a consistent and unified URL structure across our application. By leveraging this technique, we can enhance the organization and readability of our routes, making it easier to manage and maintain our application.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Share:

Subscribe
guest
Label
0 Comments
booklet-200px-width-min.png

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices.

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2023

wpDiscuz


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK