简体   繁体   中英

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?}");
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM