| by Achyut Kendre | No comments

How to implement End Point Routing in ASP.NET Core?

ASP.NET Core 3.1
Understand End Point Routing in Detail

What is End Point Routing?

Endpoint routing is a feature newly introduced in ASP.NET Core that enables you to provide routing information to middleware in the request processing pipeline. Before the introduction of endpoint routing, routing resolution in ASP.NET Core MVC was performed at the end of the request processing pipeline. As a result, route information (such as which action method needs to be executed) was unknown to any middleware processing a request before the MVC middleware in the request processing pipeline. Incidentally, endpoint routing is available as part of ASP.NET 3.0 and later versions.

How to Activate the End Point Routing in ASP.NET Core?

To use the End Point Routing ASP.NET Core 3.x, we need to follow 2 step process –

Step 1: Add a service in Configure method we have following two options in asp.net core 3.x.
> AddControllers()
> AddControllersWithViews()
Step 2: Inject Middleware for Routing in ConfigureServices Method.
> UseRouting()
> UseEndPoints()

Let us understand it step by step.

How to Activate MVC using AddControllers() in ASP.NET Core 3.x?

  • It was introduced in ASP.NET Core 3.0
  • It adds everything that AddMvcCore() does
  • API explorer – required if you want to build dynamic API documentation, generate Swagger/OpenAPI files
  • Data Annotations – needed for model validation
  • Formatter mappings – needed for content negotiation to work
  • CORS – Cross origin Request support.
  • Most comfortable setup for API development.
  • None of the view services are registered here

How to Activate MVC using AddControllersWithViews() in ASP.NET Core 3.x?

  • It adds everything that AddControllers() does
  • Add views functionality – explicitly registers the Razor view engine
  • cache tag helper
  • This should be the default choice for you if you do not need the new Razor pages functionality
public void ConfigureServices(IServiceCollection services)
        {
            //register basic mvc + api features
            //   services.AddControllers();
            //regsiter full mvc + api features
            services.AddControllersWithViews();
        }

UseRouting() & UseEndPoint() Middleware

Routing activity in endpoint routing is divided into two steps, first to just match the request and in second step it execute the route. It can be done using these two middleware –

UseRouting():- this middleware will match the request url to the specific EndPoint defined.
UseEndPoint():- this middleware will actually execute the matched endpoint.

Why End Point Routing in ASP.NET Core 3.x?

ASP.NET core got various technologies or API’s for various types o application like –

  • Controllers
  • Razor Pages
  • SignalR
  • gRPC Services
  • Endpoint-enabled middleware such as Health Checks.
  • Delegates and lambdas registered with routing.

So it is divided into two step, since it is not only MVC.

  • Prior to endpoint routing the routing resolution for an ASP.NET Core application was done in the ASP.NET Core MVC middleware at the end of the HTTP request processing pipeline.
  • This meant that route information, such as what controller, action would be executed, was not available to middleware that processed the request before the MVC middleware in the middleware pipeline.
  • Endpoint routing also allows us to decouple the route matching logic from the MVC middleware, moving it into its own middleware.
  • It allows the MVC middleware to focus on its responsibility of dispatching the request to the particular controller action method that is resolved by the endpoint routing middleware.

Types of Routing

There are two types of routing for action methods:
Conventional Routing :- we define the url pattern that will be get registered to route table with which request will be matched.
Attribute Routing :- In this routing we define url pattern directly on action that will be used by UseRoutingMiddleware to match the request.

Conventional Routing in ASP.Net Core 3.x

Inside the call to UseEndpoints(), we use the MapControllerRoute() method to create a route by giving the name default.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints =>            {
                endpoints.MapControllerRoute(
                     name:"default",
                     pattern:"{controller=Home}/{action=Index}/{id?}"
                    );
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

Leave a Reply