What is Endpoint Routing, Implementing it from start [with codes]

What is Endpoint Routing, Implementing it from start [with codes]
ASP.NET Core 3.0 brings a new concept of Endpoint routing which provides routing information to middlewares in the Startup.cs class. This feature was not there in the ASP.NET Core 2.0 and earlier versions. To understand it, see the below code that tries to find out the Controller’s name, in the Configure method of the Startup.cs file.
app.Use(async (context, next) =>
{
    var controller = context.Request.RouteValues["controller"];
    await next();
});
In this scenario I get null value for the controller variable, and this is shown by breakpoint value as illustrated in the below image:
Null value for controller without endpoint routing
If you did not understand where to put this code, I am giving you the full code of my Configure method below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStaticFiles();

    app.Use(async (context, next) =>
    {
        var controller = context.Request.RouteValues["controller"];
        await next();
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Now using Endpoint Routing Now in your ASP.NET Core 3.0 or later version project, add the same code (making use of Enpoint Routing) to the Configure method as shown below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStaticFiles();

    app.UseRouting();
    
    app.Use(async (context, next) =>
    {
        var controller = context.Request.RouteValues["controller"];
        await next();
    });

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
	   name: "default",
	   pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
Run the application and check the value of ‘controller’ through the breakpoint. This time you will get the value of the controller in the variable. This is all due to Endpoint routing. Check the below image that shows the breakpoint’s value:
Value of controller by endpoint routing
I have covered Routing feature of ASP.NET Core in great details. It contains 5 important topics which are:

Implementing Endpoint Routing

By default the ASP.NET 3.0 and later versions have Endpoint routing enabled. You only have to add app.UseRouting()’ in the Configure() method of the Startup.cs file, before any other middleware that needs to access routing:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //Define this before other middleware that needs routing access                  app.UseRouting();
    // Here add middlewares that needs routing access
    app.UseEndpoints(endpoints =>
    {
        //Define endpoint routes here
        endpoints.MapControllerRoute(
	   name: "default",
	   pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Endpoint routing’s two extension methods are:

  • UseRouting: It matches request to an endpoint.
  • UseEndpoints: It execute the matched endpoint.
An endpoint represents the URL to the route that matches the request.
The new thing is that the routing is decoupled from the specific ASP.NET Feature. In the previous Versions, every feature (MVC, Razor Pages, SIgnalR, etc.), had it’s own endpoint implementation. Now the endpoint and routing configuration can be done independently.

Route Configuration Extension Methods In UseEndpoints() method

Endpoint routing supports many route configuration methods, some important ones are:
MapControllerRoute()
Adds endpoints for controller actions and specifies a route with the given name, pattern, constraints, etc. Sample endpoint configuration as below:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
	 pattern: "{controller=Home}/{action=Index}/{id?}");
});
MapRazorPages()
This sets the endpoint routing for Razor Pages. Sample endpoint configuration as below:
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
});
MapRazorPages()
Adds a route that only matches HTTP GET requests. The code given below will show the ‘Hello world’ message for the root page of the website in the browser:
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", context => context.Response.WriteAsync("Hello world"));
});

Similarly, we can configure other Http verb route like MapPost, MapDelete, MapPut, etc.

Where to use Endpoint Routing

Endpoint routing makes the ASP.NET Core framework more flexible since it decouples the route matching and resolution functionality from the endpoint dispatching functionality, which until now was all bundled in with the MVC middleware.

Let’s take a few examples to understand them:

CORS
Suppose you have to enable CORS only on a single endpoint. You can do this simply as:
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/someurl", context => context.Response.WriteAsync("Hello world")).RequireCors("policy-name");
});
I have also written a details tutorial on CORS which you will certainly like to read – How to Enable Cross-Origin Requests (CORS) in ASP.NET Core
Authorization
You can also enable Authorization on a single endpoint so that only ‘Admin’ roles are able to view the corresponding URL like this:
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/secured", 
        context => context.Response.WriteAsync("Secured Page"))
        .RequireAuthorization(new AuthorizeAttribute() { Roles = "admin" });
});
Redirection in ASP.NET Core

You already know that when there are more than one routes defined in an application, then the routes are applied in the order in which they are defined. You can now override this thing as you have prior information about a lot of route things.

The process of implementing ASP.NET Core Model Validation is never been so easy if you check out this tutorial.
Check the below code where I am redirecting users to /contact page when Controller called is ‘Business’ and action method is ‘Deal’.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//Define this before other middleware that needs routing access                  app.UseRouting();
    
    // Redirect code
    app.Use(async (context, next) =>
    {
      var controller = context.Request.RouteValues["controller"];
      var action = context.Request.RouteValues["action"];
      if ((controller.ToString() == "Business") && (action.ToString() == "Deal"))
      {
          context.Response.Redirect("/contact");
      }
      await next();
    });

    app.UseEndpoints(endpoints =>
    {
        //Define endpoint routes here
        endpoints.MapControllerRoute(
	   name: "default",
	   pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
You can download the full source code of this tutorial: Download
Simplifying Dependency Injection
If you have worked with Dependency Injection (DI) feature of ASP.NET Core then you had come across a situation where you need to add context information to a service. Then this service is made available to the controller using DI. Here you can make use of Endpoint routing quite easily and bypass the complexities of Dependency Injection. This situation is explained by Rick Strah in his blog very well.

How to update your routes

Updating your older routes to Endpoint routing is easy. Go to the Startup.cs file where your old routes are written. You only have to add all the routes inside the app.UseMvc() method to inside the endpoints.MapControllerRoute() method. See –
app.UseEndpoints(endpoints =>
{
    // add the old routes
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
However if you want to keep working with your old routes then you can disable the Endpoint routing from the ConfigureServices() method:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(option => option.EnableEndpointRouting = false); // disable endpoint routing
}
Conclusion

Endpoint routing allows ASP.NET Core applications to determine the endpoint that will be dispatched, early on in the middleware pipeline, and so makes the framework more flexible.

I hope you liked this tutorial, so please share this on your facebook and twitter accounts, and let the knowledge flows

Next important tutorial: Implementing CORS in ASP.NET Core

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *