Saturday, April 15, 2023

How do you configure routing in ASP.NET Core?

Routing in ASP.NET Core is responsible for mapping incoming HTTP requests to the appropriate action methods in a controller. By default, ASP.NET Core uses a set of conventions to determine which action method to execute based on the request URL and HTTP verb. However, you can customize the routing behavior by configuring the routing middleware in the Configure method of your Startup class.

Here's an example of how to configure routing in ASP.NET Core:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseRouting();

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



In this example, the UseRouting method is called to enable routing middleware. The UseEndpoints method is then called to define the endpoints for the application. The MapControllerRoute method is used to map incoming requests to action methods in a controller.

The MapControllerRoute method takes three arguments:name: A unique name for the route.
  • pattern: The URL pattern that the route will match. This pattern can include placeholders for route parameters, which are enclosed in curly braces ({}).
  • defaults: An object that specifies default values for route parameters.

In this example, the default route is defined with a URL pattern of "{controller=Home}/{action=Index}/{id?}". This means that if no controller or action is specified in the URL, the HomeController and Index action method will be used by default. The id parameter is optional and can be omitted from the URL.

You can define multiple routes by calling the MapControllerRoute method multiple times with different patterns and names. The ASP.NET Core routing system will try to match incoming requests to the defined routes in the order that they are defined, using the first route that matches.

You can also define routes using attributes on the controller and action methods. This is known as attribute routing and provides a more explicit way to define the URL patterns for your application. To enable attribute routing, call the AddControllers method with the [ApiController] attribute in the ConfigureServices method:

 public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddControllers().AddNewtonsoftJson();

    // ...
}



Then, decorate your controller and action methods with the [Route] attribute:

[Route("api/[controller]")]
public class MyController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        // ...
    }

    [HttpPost]
    public IActionResult Post([FromBody] MyModel model)
    {
        // ...
    }
}
 

In this example, the MyController class is decorated with the [Route] attribute with a template of "api/[controller]", which means that all URLs for this controller will begin with "api/" followed by the controller name. The HttpGet and HttpPost attributes are used to define the HTTP verb and URL pattern for each action method. The {id} placeholder in the HttpGet attribute represents a route parameter that will be passed to the Get method as an argument. 

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.