HJ1990
HJ1990

Reputation: 415

ASP.NET Core 3.1 : how to route to a controller in a sub folder

How can I set up a default routing if the controller is inside a subfolder? Currently, running the code shown here, I get an error

localhost page can't be found

My folder structure is set up like this:

Project Name    
    > API
        > Controllers   
            > ProductsController

ProductsController

[Area("API")]
[Route("products")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    [Route("list")]
    public ActionResult<List<Product>> GetProductsList()
    {
        var products = _context.Products.ToList();
        return Ok(products);
    }
}

Startup.cs

app.UseEndpoints(endpoints =>
{
    endpoints.MapAreaControllerRoute(
    name: "MyProducts",
    areaName: "API",
    pattern: "{controller=products}/{action=list}/{id?}");
});

Upvotes: 1

Views: 2149

Answers (1)

Sherif Elmetainy
Sherif Elmetainy

Reputation: 4502

The [Route("products")] in your code will cause the controller to be available at URL /products instead of /api/products

To fix change it to [Route("[area]/[controller]")] or [Route("api/products")].

Edit: By the way, the folder structure of your C# files in your project has no effect in runtime, since they all get compiled in a DLL. So you can layout the C# files the way you see logical without worrying about runtime effects.

Upvotes: 4

Related Questions