What is Routing? Different ways to build Routing in ASP.net Core.
Routing is responsible for mapping an approaching solicitation to a routes handler. Routes are characterized in the ASP.NET application and designed when the application begins up. Route can alternatively remove values from the URL contained in the demand, and these qualities can then be utilized for request processing. Utilizing routes data from the ASP.NET application, the routing usefulness is additionally ready to produce URLs that guide to routes handlers. Hence, routing can discover a routes handler in light of a URL, or the URL comparing to a given routes handler in light of routes handler data.
Different ways to build routing:
Creating Default Routes
- You can simply change the controller and action name inside Configure method in Startup.cs file.
Extending Default Routes
Once the default route set, we might need to add customized routes based on our requirements. For this, we can add routes.MapRoute() method like this.
Using Attributes
You can also set the route by using attributes in controller just before the actions.
Building RESTful Routes
In REST API, you simply add [HttpGet],[HttpPost] before the API method to define the route. Here, we are trying to call RESTful service to accept calls under the /api/values route.
Using Constraints
We can limit the kind of significant worth that we go to activities utilizing constraints. For instance, if we expect an argument that is a number we need to limit it to an integer type. Define constraints in attributes utilizing curly brackets {id:int}.
Here, we are calling the action GetBookByID which will acknowledge just an integer. Adding a question mark to the constraints {id:int?} shows that the parameter is not obligatory. In this way, we can call the method GetBookByID/123 or only GetBookByID without extra parameters. We can likewise declare constraints in default routes defined in the Startup class along these lines: