| by Achyut Kendre | No comments

What is End Point Routing in ASP.NET Core?

End Point Routing in ASP.NET Core
End Point Routing in ASP.NET Core

Example Code: https://drive.google.com/file/d/1x4ve8sjVHs_PNDRN9ZEDWdLQ0LrEUvmt/view?usp=sharing

Endpoint routing is a feature newly introduced in ASP.NET Core 3.0 that enables you to provide routing information to middleware in the request processing pipeline. ASP.NET Core MVC 2.1 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 MVC in ASP.NET Core 3.x?

To activate MVC in ASP.Net Core 3.x we have following to methods and you need to call any one of them in Configure method of startup class –

  1. AddControllers()
  2. AddControllersWithViews()

What is Difference between AddControllers & AddControllerWithViews?

First we will try to understand adbout Add Controllers method –

AddControllers(): –

  • 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.

ADdControllersWithViews()

  • 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.

Why End Point Routing in ASP.NET Core?

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.

How to Use End Point Routing in ASP.NET Core 3.x?

To use the endpoint routing in asp.net core 3.x , we have two methods userouting() and useendpointrouting() methods you need to call these methods in ConfigureServices method of Startup class. You need to remember you should call userouting() method before usenedpoinrouting()

UseRouting() & UseEndPointRouting() Middleware

In case of ASP.Net Core 3.x the routing two activities matching activity and executing activity are seperted from each other so we need to inject two middleware in request pipeline.

Routing Middleware using UseRouting():-

UseRouting() middleware method will inject Routing Middleware whose responsiblity is just to match the request to end point.

End Point Routing Middleware using UseEndPointRouting():-

UseEndPointRouting() method will inject the End Point Routing Middleware in request pipeline whose responsibility is to execute the route request.

End Point Routing Example in ASP.NET Core

1 .Create a new asp.net core empty project using visual studio 2019.

2. Register MVC to IoC container using a method AddControllers() as follow –

public void ConfigureServices(IServiceCollection services)
        {
            //register basic mvc + api features
               services.AddControllers();
        }

3. Inject Routing and End Point Routing Middleware in ConfigureServices method of ASP.NET Core.

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?}"
                    );

            });

Here MapControllerRoute method will help you to create route for MVC controller action, it will add the url to route table so that it will be used for routing. This method has two parameters name and pattern. Name is unique name of route where as pattern allow you to specify the url pattern used to match request url.

Step 3: Create controllers folder and create Home controller with action to return some string as follows –

public class HomeController : Controller
    {
        public string SayHello()
        {
            return "Hello!";
        }
    }

Step 4: Run the application and call Sayhello action of Home Controller. it will work perfect.

Step 5: Add the action to home controller called index which returns view as follows –

 public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        public string SayHello()
        {
            return "Hello!";
        }
    }

When you run the project it will get you error. Why error because we had registered the mvc using method AddControllers to IoC it will not give you a view functionality. If you want to have a view functionality you need to modify the Configure method Startup class and use AddControllersWithViews() method to get full MVC.

 public void ConfigureServices(IServiceCollection services)  {
      services.AddControllersWithViews();
 }

Types of Routing Supported by ASP.Net Core

There are two types of routing for action methods:
1. Conventional Routing :- we define the url pattern that will be get registered to route table with which request will be matched.
2. 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 conventional routing we define a url pattern using a method MapControllerRoute()  inside a UseEndPoint() method that will be get registered to RoutTable and request url will be matched to this pattern and specific cation of specific controller will be get called. It can be done as follows –

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                     name:"default",
                   pattern:"{controller=Home}/{action=Index}/{id?}"
                    );
            });

Attribute Routing

In attribute routing we do not need to register the url patterns to route table and then do the match. It is very flexible and easy. In Attribute routing we can define the url pattern directly on action using a built in attribute [Route]. You can activate the attribute routing as follows –

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

MapControllers() method will activate the attribute routing in asp.net core 3.x application, after activation you can use [Route] Attribute on any controller and action as follows –

[Route("ho/ind")]
public IActionResult Index()
{
return View();
}

So index action can be called using url ho/ind.

You can also define multiple url to one action using attribute routing.

[Route("ho/ind")]
[Route("h/index")]
public IActionResult Index()
{
 return View();
}

In this you can call index action using url h/index as well as ho/ind both.

You can also define the parameters in URL

[Route("ho/say/{str}")]
[Route("hom/{str}/say")]
public string SayHello(string str)
{
 return "Say Hello Called for :=>" + str;
}

In this str is url parameter and you can pass any value to the str parameter.

You can also define the restriction /constraints to the url parameters as follows

[Route("ho/bye/{n:int:min(10):max(20)}")]
public string SayBye(string n)
{
return " n value is:" + n;
}

here we had added restriction that n is url parameter and it should be integer and the minimum alue for n can be 10 or maximum value for n can be 20.