Routing In Asp.Net core By Sagar Jaybhay

All About Attribute,Default & Token Routing In Asp.Net Core By Sagar Jaybhay

There are 2 types of routing Present in Asp.Net Core.

  • Conventional Routing
  • Attribute Routing

In MVC core routing is a middle-ware and it is present in a start-up class file. In MVC controller which handles the incoming request and invoke appropriate method. There are 2 ways by which MVC routing enable in our application. Mapping is done by Routing Rules. In the old version of asp.net, we have a route.config file separate for routing but in this, we have to write this in Configure method of startup class.

  1. UseMvcWithDefaultRoute
  2. UseMvc

These are 2 methods by which MVC routing in enable in our web application.

UseMvcDefaultRoute

This is an extension method which adds MVC support in our application. If you comment this line then the application does not have MVC support. UseMvcDefaultRoute is the default method by which routing is enabled. Below is the code for that.

    public class Startup
    {
        private readonly IConfiguration _config;

        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<IStudentRepository,StudentRepo>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
            
            app.Run(async (context) =>
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
    }

In startup class’s Configure method we the method is present.

routing in asp.net core
url structure in asp.net core 2

https://localhost:44385/home/index this the URL of application in that localhost:44385 is the server address and home it is controller and index is that action method present in the controller.

default route in asp.net core

In this image, the default route method is added. Configure method is use full for setup request pipeline. In this, we don’t need to explicitly write the route. As an image highlighted the text default route present in this method.

UseMVC

This is also an extension method which is like UseMvcWithDefaultRoute but it only adds MVC support and in this default route is not configured for our application.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseMvc(routes=> {
                routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
            });
           
            
            app.Run(async (context) =>
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

By which you enable routes which configure a route. UseMvc is used and took one overloaded method which is IRouteBuilder parameter and this is used to add route by MapRoute method as shown above. In this we mark {id?} this means it is optional.

But above code not add default route in our application and it goes to last middleware where return response sagar jaybhay. So go to the home controller of index method we need to configure this like below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseMvc(routes=> {
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
           
            
            app.Run(async (context) =>
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

In this, we set default controller name and action name to this so that if we do not provide any controller and method then it will go to the default path.

Attribute Routing  MVC

Mostly attribute routing is used for rest API in mvc application but you can use for general asp.net application. To enable attribute route you can remove usedefaultroute method from asp .net core startup class of configure method.  And simply use UseMVC() without a parameter method.

Below startup class file code

public class Startup
    {
        private readonly IConfiguration _config;

        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<IStudentRepository,StudentRepo>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            //app.UseMvc(routes=> {
            //    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            //});

            app.UseMvc();
            
            app.Run(async (context) => 
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
    }

To add route attribute with pathname on the action method as shown below code.

public class HomeController: Controller
    {
        private IStudentRepository _repository;
        
        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }     

        [Route("Home/Index")]
        public ViewResult Index()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }

        [Route("Home/List")]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
        [Route("Home/Details/{id?}")]
        public ViewResult Details(int id)
        {           
            HmDetailsVM hmDetailsVM = new HmDetailsVM();
            hmDetailsVM.student = _repository.GetStudents(id);
            hmDetailsVM.DivisonOfStudent = "9-A";
            ViewBag.TitleNew = "Student Info";

            return View(hmDetailsVM);
        }
    }

Now in above code, we are repeating Route(“Home”) several time so we need to minimize that repeating name to that we have to add our Route(“Home”) to the home controller like below code.

[Route("Home")]
    public class HomeController : Controller
    {
        private IStudentRepository _repository;
        
        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }     

        [Route("Index")]
        public ViewResult Index()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }

        [Route("List")]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
        [Route("Details/{id?}")]
        public ViewResult Details(int id)
        {           
            HmDetailsVM hmDetailsVM = new HmDetailsVM();
            hmDetailsVM.student = _repository.GetStudents(id);
            hmDetailsVM.DivisonOfStudent = "9-A";
            ViewBag.TitleNew = "Student Info";

            return View(hmDetailsVM);
        }
    }

Now in this, we have not added default route in our application to add this we need to use

[Route(“)] this type of attribute but in this also we get an error because we specify Route attribute on the home controller also so that it will give an error. To remove error we need to bypass that behavior need to use [Route(“~/”)] as shown below.

[Route("Home")]
    public class HomeController : Controller
    {
        private IStudentRepository _repository;
        
        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }     

        [Route("")]
        [Route("~/")]
        [Route("Index")]
        public ViewResult Index()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }

        [Route("List")]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
        [Route("Details/{id?}")]
        public ViewResult Details(int id)
        {           
            HmDetailsVM hmDetailsVM = new HmDetailsVM();
            hmDetailsVM.student = _repository.GetStudents(id);
            hmDetailsVM.DivisonOfStudent = "9-A";
            ViewBag.TitleNew = "Student Info";

            return View(hmDetailsVM);
        }
    }

Attribute routing is good for rest API and also if your controller methods return some for JSON or XML data not view it is valid for the view but mostly use for returning JSON data.

Token routing

Now in above, we are using a route to take in consideration that controller name and action name never change but if some requirement comes and your action name and controller name needs to change in that case our route will fall for that reason we need use Token routing. In this token routing, we specify controller and action keywords in Route attribute like below so in case your controller name and action name changed it will take appropriately.

[Route("[controller]")]
    public class HomeController : Controller
    {
        private IStudentRepository _repository;
        
        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }     

        [Route("")]
        [Route("~/")]
        [Route("[action]")]
        public ViewResult Index()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }

        [Route("[action]")]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
        [Route("[action]/{id?}")]
        public ViewResult Details(int id)
        {           
            HmDetailsVM hmDetailsVM = new HmDetailsVM();
            hmDetailsVM.student = _repository.GetStudents(id);
            hmDetailsVM.DivisonOfStudent = "9-A";
            ViewBag.TitleNew = "Student Info";

            return View(hmDetailsVM);
        }
    }

Points to Remember on Attribute  routing:

  1. The route attribute is used to define routes
  2. Route attribute can be applied on the controller or the controller action methods in asp.net Core MVC.
  3. Attribute routing gives more flexibility than conventional routes.
  4. Attribute routes mostly used for rest API.
  5. Attributes routes are hierarchical.
  6. If the controller action method routes combine with / or ~/ then it Is not combine with the controller route attribute.

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts