Conventional routing

The conventional routing is the default routing approach in ASP.NET Core. As we have already seen, this approach uses the app.UseEndpoints extension method in the Startup class to declare routing templates:

    app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}");
});

By default, ASP.NET Core applies the default route template to the routing engine, which maps each segment of our URL with the controller name, the action name, and the id name, respectively. Furthermore, it is possible to define multiple routes in our application by adding them to the routing builder in the Startup class:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}");

endpoints.MapControllerRoute("order", "order/givemeorders", new { controller = "Order", action = "Get" });
});

In this case, the https://myhostname/order/givemeorders route will be mapped to the Get action of OrderController. We should notice that the routing template example we defined in the preceding code is not compliant with the REST architectural style. Accordingly, it doesn't respect the 2nd level of the Richardson Maturity Model, as mentioned in Chapter 1, REST 101 and Getting Started with ASP.NET Core. Furthermore, if we apply the default routing template to OrderController we discussed in previous chapters, the Get action method will respond to the following URI: https://localhost/order/get.

To make our routing template compliant with the Richardson Maturity Model, let's introduce the Map method that's provided by ASP.NET Core. It is possible to map different HTTP verbs using routing templates, as follows:

app.UseEndpoints(endpoints =>
{
endpoints.MapGet("order", context => context.Response.WriteAsync("Hi, from GET verb!"));
endpoints.MapPost("order", context => context.Response.WriteAsync("Hi, from POST verb!"));
});

The MapGet, MapPost, MapPut, and MapDelete methods accept the route template as the first parameter and a RequestDelegate method, which provides a way to handle HttpContext of the current request. However, it is not possible to call the OrderController logic in RequestDelegate because there isn't an effortless way to access the controllers' instances from the context. Therefore, there isn't an easy way to implement a REST-compliant routing system using conventional routing. In general, conventional routing is mainly designed for web applications that serve views and HTML. An alternative solution is to use the attribute routing technique, which is the most solid way to implement controllers' routing in a web services context.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.127.141