06
JunRouting is a pattern matching system that monitors the incoming request and figures out what to do with that request. Typically, it is a way to serve the user request.

When a user request URLs from the server then URLs are handled by the routing system. The Routing system try to find out the matching route pattern of requeted Url with already registered routes which are map to controller, actions, files, or other items. If there is a matching route entry, then it process the request i.e. serve the resource, otherwise it returns 404 error.

Types of Routing
There are two main ways to define routes in ASP.NET Core:

Convention-based Routing
It creates routes based on a series of conventions which represent all the possible routes in your system. Convention-based are defined in the Startup.cs file.
Conventions based Routing Configuration & Mapping


Attribute Routing
It creates routes based on attributes placed on controller or action level. Attribute routing provides us more control over the URLs generation patterns which helps us in SEO.

Attribute Routing Tokens
One of the cool thing about ASP.NET Core routing is it's more flexible as compared to ASP.NET MVC5 routing since it provides tokens for [area], [controller], and [action]. These tokens get replaced by their values in the route table.

Mixed Routing
You can use Convention-based Routing and Attribute routing together. Even you should use both together since it's not possible to define attribute route for each and every action or controller. In that case, Convention-based Routing will help you.
Route Constraints
Route Constraints are used to restrict the type of passed value to an action. For example, if you expect an argument id as an integer type, then you have to restrict it to an integer type by using datatype in the curly brackets as {id:int}.
Following are the main route constraints you can use:
:int
:bool
:datetime
:decimal
:guid
:length(min,max)
:alpha
:range(min,max)
Optional Parameters
You can define your route parameter as optional in routes by adding a question mark (?) to the parameter's constraint as given below:
app.UseMvc(routes => { routes.MapRoute( template: "{controller}/{action}/{id:int?}"); });
Default Values
In addition to route constraints and optional parameters, you can also specify the default values for your route parameters which will be used if values are not provided.
app.UseMvc(routes => { routes.MapRoute( template: "{controller=Home}/{action=Index}/{id:int?}"); });
What do you think?
This article is meant to be a getting started to the concept of Routing. It's meant to show the most common uses, not all of them. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.