Sunday 27 September 2020

ASP.NET Core MVC: Routing

 What is Routing in ASP.NET Core MVC?

Routing is the process through which the application matches an incoming URL path and executes the corresponding action methods. ASP.NET Core MVC uses a routing middleware to match the URLs of incoming requests and map them to specific action methods.

So, the ASP.NET Core Framework maps the incoming Requests i.e. URLs to the Controllers action methods based on the routes configured in your application. You can configure multiple routes for your application and for each route you can also set some specific configurations such as default values, constraints, message handlers, etc.

There are two types of routing for action methods:

  1. Conventional Routing
  2. Attribute Routing

In Conventional Based Routing, the route is determined based on the conventions defined in the route templates which will map the incoming Requests (i.e. URLs) to controllers and their action methods. In ASP.NET Core MVC application, the Convention based Routes are defined within the Configure method of the Startup.cs class file.

In Attribute-Based Routing, the route is determined based on the attributes which are configured either at the controller level or at the action method level. We can use both Conventional Based Routing and Attribute-Based Routing in a single application.

Understanding the Default Route in ASP.NET Core MVC Application:

 We can add the required MVC middleware into the request processing pipeline either by calling the UseMvcWithDefaultRoute() method or by calling the UseMvc() method within in the Configure() method of the Startup.cs class file as shown in the below code. As of now, we are using the UseMvcWithDefaultRoute() middleware.

public void Configure(IApplicationBuilder app) { 
    
    app.UseDeveloperExceptionPage(); 
    app.UseFileServer(); 
    app.UseMvcWithDefaultRoute();   
}

Let us have a look at the implementation of the UseMvcWithDefaultRoute() method by visiting the following GitHub URL.

As you can see in the above implementation, this method internally calls the UseMvc() method which will add the default route into the application’s request processing pipeline. 

Understanding The Route Template:

The above default route template maps most URLs that have the following pattern.

http://localhost:52190/Student/Details/2
http://localhost:52190/Student/Details

This gives us a default routing rule that allows us to get to the HomeController. Instead of using the UseMvcWithDefaultRoute, let us use the UseMvc, and then configure the route at this point using a named method ConfigureRoute. The following is the implementation of the Startup.cs file.

     
     public void ConfigureServices(IServiceCollection services) { 
         services.AddMvc(); 
      }  
        
      // This method gets called by the runtime.  
      // Use this method to configure the HTTP request pipeline. 
      public void Configure(IApplicationBuilder app) { 
         app.UseDeveloperExceptionPage(); 
         app.UseFileServer(); 

         app.UseMvc(ConfigureRoute);  
      } 
 
      private void ConfigureRoute(IRouteBuilder routeBuilder) { 
         //Home/Index 
       routeBuilder.MapRoute("Default""{controller = Home}/{action = Index}/{id?}");
      } 

Inside the ConfigureRoute method, you can configure your routes; you can see that this method has to take a parameter of type IRouteBuilder. The goal of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller that can respond to that request.

When using attribute-based routing you would mention route on your controller or the action method. You can define multiple routes for the same action method. Here is an example that illustrates this.

public class HomeController : Controller
{
    [Route("")]
    [Route("Home")]
    [Route("Home/Index")]
    public IActionResult Index()
    {
        return View();
    }
     [Route("Home/GetAuthor/{id:int}")]
    public IActionResult GetAuthor(int id)
    {
        ViewBag.Id = id;
        return View();
    }
}


Use endpoint routing in ASP.NET Core 3.0 MVC

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

Route definitions in ASP.NET Core 3.0 MVC

When you create a new ASP.NET Core 3.0 MVC application, a default route will be created for you by Visual Studio. This is how it would look.

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

The route definition shown here consists of two parameters — the name of the route and the route pattern. This route will match the following URLs.

/Home/Index
/Author/Index
/Author/Index/12

Note that the UseRouting middleware should be configured ahead of all other middleware including authentication, authorization, and any custom middleware. By contrast, the UseEndpoints middleware should be configured at the end. The following code snippet illustrates this.

public void Configure(IApplicationBuilder appIWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
               endpoints.MapControllerRoute(
               name"default",
               pattern"{controller=Author}/{action=GetAuthor}/{id?}");
            });
        }

Inside the call to UseEndpoints, MapControllerRoute is used to create a single route. The single route is named default route. Most apps with controllers and views use a route template similar to the default route. REST APIs should use attribute routing.

Multiple conventional routes

Multiple conventional routes can be added inside UseEndpoints by adding more calls to MapControllerRoute and MapAreaControllerRoute. Doing so allows defining multiple conventions, or to adding conventional routes that are dedicated to a specific action, such as:

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(name"blog",
                    pattern"blog/{*article}",
                    defaultsnew { controller = "Blog"action = "Article" });
        endpoints.MapControllerRoute(name"default",
                    pattern"{controller=Home}/{action=Index}/{id?}");
    });

The blog route in the preceding code is a dedicated conventional route.

Important: 

Routing is configured using the UseRouting and UseEndpoints middleware. To use controllers:

  • Call MapControllers inside UseEndpoints to map attribute routed controllers.
  • Call MapControllerRoute or MapAreaControllerRoute, to map both conventionally routed controllers and attribute routed controllers.

Refrence: https://dotnettutorials.nethttps://www.infoworld.comhttps://docs.microsoft.com


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives