Routing in MVC – Various Methods Available in ASP.NET core

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

url-routing

Routing in Microsoft MVC or WebAPI applications serves as a map to define the routes for all incoming requests. There are three basic components of routing in MVC & WebAPI applications Controller, Action method, and parameters.

Example:

https://www.betechnical.blog/account/login/24

In the above URL, account is a controller, login is the action method and 24 is a parameter/query string.

Now, Let’s go through different ways to build routing in ASP.NET CORE.

Routing in MVC by Creating Default Routes

By convention, you can define the default route in your project’s startup class.

public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
      services.AddMvc();
   }

   public void Configure(IApplicationBuilder app, 
                         IHostingEnvironment env, 
                         ILoggerFactory loggerFactory)
   {

      app.UseMvc(routes =>
      {

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

       });

    }
}

Make sure that essential configuration for MVC pattern of Controller+Action+ID routes exist in the project. In addition, you can also declare routing pattern like this:

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

Routing in MVC by Extending Default Routes

On specific needs, you can extend a default route by adding customized routes. For this, add a configuration by using the MapRoute() method:

app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }
    );

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

On the Home controller, adding extra route allows access to About action with an/about the route. About page can be still accessed with conventional/home/about the route as the default pattern route is still present.

Routing in MVC by Using Attributes

Additionally, you can also configure routes using attributes in controller and actions.

[Route("[controller]")]
public class AnalyticsController: Controller
{

    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}

Now, you can access controller actions through the following routes:

  • /Analytics/Dashboard
  • /Analytics/Charts

Two tokens [controller] and [action] show that we have to refer to the declared controller and action name. In this route, “Analytics” is the name of the controller, and “Charts” the name of the action.

By Building RESTful Routes

We need to use the following route configuration to declare a RESTful controller.

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable Get()
    {
        return new string[] {"hello", "world!"};
    }

 
    // POST api/values
    [HttpPost]
    public void PostCreate([FromBody] string value)
    {

    }
}

Here, RESTful service is told to accept calls under the /api/values route. Now, we do not use the Route attribute for actions. Instead, we decorate it with HttpGet, HttpPost, HttpPut, and HttpDelete attributes.

Do you think this was a useful article for you? Feel free to provide your comments and concerns in the below comment section.
[yikes-mailchimp form=”1″]

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on whatsapp
Share on email
Author Bio

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recommended for you
Connect With Us
Stay Connected

Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.

Latest Articles
Featured image
Business

The Rise of Virtual Assistants (Infographic)

Small companies and start-up businesses resort to hiring virtual assistants as a solution to the limited time they have available. Here are some of the trends of why hiring or being a virtual assistant may be a good idea:

Free hub for guest blogging nerds and newbie writers

  • Submit Guest Post
  • Share your Knowledge
  • Build your Backlinks
  • Advertise your products
  • Make money by writing
Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.