简体   繁体   English

ASP.NET Core 3.1:如何路由到子文件夹中的 controller

[英]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?如果 controller 在子文件夹中,如何设置默认路由? 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启动.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您的代码中的[Route("products")]将导致 controller 在 URL /products而不是/api/products

To fix change it to [Route("[area]/[controller]")] or [Route("api/products")] .要修复将其更改为[Route("[area]/[controller]")][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.编辑:顺便说一句,项目中 C# 文件的文件夹结构在运行时没有影响,因为它们都在 DLL 中编译。 So you can layout the C# files the way you see logical without worrying about runtime effects.因此,您可以按照您看到的逻辑方式对 C# 文件进行布局,而无需担心运行时影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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