Reader small image

You're reading from  Learning ASP.NET Core MVC Programming

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786463838
Edition1st Edition
Languages
Right arrow
Authors (2):
Mugilan T. S. Ragupathi
Mugilan T. S. Ragupathi
author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

Anuraj Parameswaran
Anuraj Parameswaran
author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran

View More author details
Right arrow

Chapter 7. Routing

Routing is one of the important concepts in the ASP.NET MVC application as it takes care of incoming requests and maps them to the appropriate controller's actions.

In this chapter, we are going to learn about the following topics:

  • Using the MapRoute method to configure routing

  • Different types of routing with examples—convention and attribute-based

  • Using HTTP verbs in attribute-based routing

We briefly discussed routing in Chapter 3 , Controllers. In this chapter, we are going to discuss routing along with several options available to customize it in ASP.NET Core.

Convention-based routing


The routing engine is responsible for mapping the incoming requests to the appropriate action method of the controller.

In the Configure method of the Startup class, we have mapped the following route:

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

The MapRoute method has two parameters:

  • name: This represents the name of the route as we could configure multiple routes for the same application.

  • template: This signifies the actual configuration for the route. There are three parts to this configuration value. As we are supplying default parameters, if the values are not passed, it will take the default parameter values.

  • {controller=Employee}: The first value acts as the name of the controller and we use the Employee controller as the default controller when the controller value is not available in the URL.

  • {action=Index}: The Index action method...

Attribute-based routing


Until now, we have used convention-based routing. In convention-based routing, we define the routing templates (which are just parameterized strings) in a centralized place these are applicable to all the available controllers. The problem with convention-based routing is that, if we want to define different URL patterns for different controllers, we need to define a custom URL pattern that is common to all the controllers. This makes things difficult.

There is another option for configuring the routing engine-attribute-based routing. In attribute-based routing, instead of configuring all the routing in a centralized location, the configuration will happen at the controller level.

Let us see an example of attribute-based routing.

First, let us remove the convention-based routing that we created earlier in the Configure method in the startup.cs class file:

public void Configure(IApplicationBuilder app) 
    { 
        app.UseIISPlatformHandler(); 
     ...

Route attribute at the controller level


You will notice that, with the URL pattern for the action methods, Index and Index2, we repeat the controller name, Home, in both URL patterns, Home and Home/Index3. Instead of repeating the controller method name (or any common part in the URL) at the action method level, we can define it at the controller level.

In the following code, the common part of the URL (Home) is defined at the controller level and the unique part is defined at the action method level. When the URL pattern is getting mapped to the action methods of the controller, both route parts (at the controller level and at the action method level) are merged and matched. So there will be no difference between the routes defined earlier and those that follow.

If you want two parameters in attribute-based routing, you can pass them within curly braces. In the following example, we did this for the SayHello action method.

For example, the URL pattern http://localhost:49831/Home/Index3, will...

Passing routing values in HTTP action verbs in the Controller


Instead of passing the routing values as Route attributes, we can even pass the routing values in HTTP action verbs such as HTTPGet and HTTPPost.

In the following code, we have used the HTTPGet attribute to pass the route values. For the Index method, we did not pass any value and hence no route value will get appended to the route value defined at the controller method level. For the Index2 method, we are passing the value Index3 and Index3 will get appended to the route value defined at the controller level. Please note that only URLs with GET methods will be mapped to the action methods. If you access the same URL pattern with the POST method, these routes will not get matched and hence these action methods will not get called.

namespace Validation.Controllers 
{     
    [Route("Home")] 
    public class HomeController : Controller 
    { 
        // GET: /<controller>/ 
        [HttpGet(...

Route Constraints


Route Constraints enable you to constrain the type of values that you pass to the controller action. For example, if you want to restrict the value to be passed to the int type int, you can do so. The following is one such instance:

[HttpGet("details/{id:int?}")] 
    public IActionResult Details(int id) 
    { 
      return View(); 
    } 

ASP.NET 5 (ASP.NET Core) even supports default parameter values so that you can pass the default parameters:

[HttpGet("details/{id:int = 123}")] 
    public IActionResult Details(int id) 
    { 
      return View(); 
    } 

Summary


In this chapter, we have learned about routing and how it works. We learned about different kinds of routing available. We discussed convention-based routing and attribute-based routing with different examples. We also discussed route constraints and the default parameter values that could be passed.

In the next chapter, we are going to see how we can make the application look good.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning ASP.NET Core MVC Programming
Published in: Nov 2016Publisher: PacktISBN-13: 9781786463838
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran