Multiple Ways to Build Routing in ASP.NET Core

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 provided link account is a controller, login is action method and 24 is parameter or query string.

Let’s review the different ways to build routing in ASP.NET CORE.

Creating Default Routes

By convention in your project’startup class, the default route can be defined.

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

       });

    }
}

We need to be sure that essential configuration for MVC pattern of Controller + Action + ID route, exist in our project. Routing pattern can also be declared like: 

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

Extending Default Routes

On specific needs, Default Route can be extended by adding customized routes. By MapRoute() method, configurations can be added:

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.

Using Attributes

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

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

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

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

Now, controller actions can be accessed through the following routes:

  • /Analytics/Dashboard
  • /Analytics/Charts

Two tokens [controller] and [action] indicate that we have to refer to the controller and action name that has been declared. In this case, “Analytics” is the name of the controller, and “Charts” the name of the action, therefore it the name of the route.

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, HttpDelete attributes

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s