ASP.NET Core Web API 如何构建 URL?

How does ASP.NET Core Web API build URLs?

我有以下代码:

[Produces("application/json")]
[Route("api/[controller]")]
public class MarketReportInstancesTableController : BaseController
{
    internal readonly MyIRIntegrationDbContext Context;

    public MarketReportInstancesTableController(ILogger<MarketReportInstancesTableController> logger,
        MyIRIntegrationDbContext context) : base(logger)
    {
        Context = context;
    }

    [HttpGet (Name ="PageData")]
    public IActionResult PageData([FromQuery] IDataTablesRequest request)
    {
    .... methd body in here
    }

然后我尝试使用 URL 访问:

http://somehost/pca/api/MarketReportInstancesTable/pagedata

这不起作用,但是

http://somehost/pca/api/MarketReportInstancesTable/

有效。

我的问题是,为什么路由会那样做?我想在同一个 WebAPI 控制器中有很多路径。

我是不是处理错了?

您的路线中没有路线模板。你只有一个路线名称

Route names can be used to generate a URL based on a specific route. Route names have no impact on the URL matching behavior of routing and are only used for URL generation. Route names must be unique application-wide.

强调我的

//GET api/MarketReportInstancesTable/pagedata
[HttpGet ("pagedata", Name ="PageData")]
public IActionResult PageData([FromQuery] IDataTablesRequest request) {
    //.... methd body in here
}

在没有路由模板的情况下使用 [HttpGet][HttpGet("")] 相同,它将映射到具有路由前缀的控制器的根目录。

这解释了为什么您的 root 调用有效。

引用Routing in ASP.NET Core

引用Routing to Controller Actions