Asp net core 3 1 how to route to a controller in a sub folder

Introduction

ASP.NET is a popular programming language used for building web . It provides a framework for developing dynamic websites, web services, and web applications. One common task in ASP.NET is , involves URLs to specific controllers and actions.

Problem

In ASP.NET Core 3.1, you may encounter a situation where you need to route to a controller that is located in a subfolder. By default, ASP.NET Core uses a convention-based routing system that maps URLs to controllers and actions based on names. However, when the controller is located in a subfolder, the routing system may not be able to find it.

Solution

To route to a controller in a subfolder in ASP.NET Core 3.1, you can use attribute routing. Attribute routing allows you to specify the route for a controller or directly in the code, rather than relying on the convention-based routing system.

To use attribute routing, you need to enable it in your ASP.NET Core application. This can be done by the following code to your Startup.cs file:

 void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();

    services.AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    });
}

Once attribute routing is enabled, you can specify the route for a controller by adding the [Route] attribute to the controller class. For , if you have a controller named HomeController located in a subfolder named Admin, you can define the route as follows:

[Route("Admin/Home")]
public class HomeController : Controller
{
    // Controller actions...
}

In this example, the route for the HomeController is set to Admin/Home. This means that the URL /Admin/Home/Index will map to the Index action of the HomeController.

You can also specify the route for individual actions within a controller by adding the [Route] attribute to the action method. For example:

public class HomeController : Controller
{
    [Route("Admin/Home/Index")]
    public IActionResult Index()
    {
        // Action logic...
    }
}

In this example, the route for the Index action is set to Admin/Home/Index. This means that the URL /Admin/Home/Index will map to the Index action of the HomeController.

Conclusion

By using attribute routing, you can easily route to a controller in a subfolder in ASP.NET Core 3.1. This allows you to organize your controllers in a hierarchical structure and define custom routes for each controller or action. Attribute routing provides flexibility and control over the routing process, making it easier to build web applications with ASP.NET Core.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents