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

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

The concept of Routing is very vast and I have covered it in 6 tutorials which are:

So make sure you cover each of these one by one.

ASP.NET Core 3.0 brings a new concept of Endpoint routing which scans incoming HTTP requests and maps them to Endpoint in the application. Endpoints can be controllers, razor pages, Blazor, SignalR and gRPC. This allows different types of Dot Net apps to work together without any problem. Endpoint Routing improves the overall routing mechanism feature in Dot Net.

In Dot Net 6.0 endpoint routing middleware wraps the entire middleware pipeline, therefore there’s no need to have explicit calls to endpoints methods described in this tutorial. Simply looks at my tutorial on ASP.NET Core Routing if you are using Dot Net 6. For Dot Net 5.0 and earlier kindly continue.

Endpoint Routing Example

To understand Endpoint Routing we create a small example. In the below code we are trying to find out the Controller’s name, in the Configure method of the Startup.cs file when not using Endpoint Routing.

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 the 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 we make use of Enpoint Routing in the Configure method of Startup class 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 we will get the value of the controller in the variable. Now we are getting a lot of information on the routes which enables us to make complex routing codes with ease.

Check the below image that shows the breakpoint’s value:

Value of controller by endpoint routing

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)
{
    app.UseRouting();
    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.
The new thing with Endpoint Routing 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, it simply allows them to coalese together.

Route Configuration Extension Methods In UseEndpoints() method

Endpoint routing supports many route configuration methods, some important ones are:

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

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)
{
    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

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Comments

  1. Syed says:

    Great article! Not just this, but all articles here are fabulous.

    My question is with endpoint routing, if I provide defaults like:
    endpoints.MapControllerRoute(
    name: “default”,
    pattern: “{controller=Admin}/{action=Index}/{id?}”);
    Why does my browser not show locahost:2131/admin/index, it only shows localhost:2131

    i searched the internet but haven’t found an answer just as yet. Pls revert!

    1. yogihosting says:

      Hello,
      Your code is looks correct, may be some issue with browser caching. Try incognito mode of the browser and see if it works.
      Thank you.

Leave a Reply

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