【问题标题】:WebApi Custom Routing in dotnet Coredotnet Core 中的 WebApi 自定义路由
【发布时间】:2019-11-05 17:33:04
【问题描述】:

在 dotnet 核心中,我正在尝试创建一个在控制器名称之前具有值的 webapi 端点。 例如:

模板:“api/{AccountId}/[控制器]”

端点“api/435ABC/Reports/EndOfYear”

我已经看到很多关于如何在 MVC 和 Framework 4.x 中执行此操作的示例,但使用 WebApi 以及我在控制器名称之前设置参数的示例并不多。

【问题讨论】:

    标签: .net-core routing asp.net-core-webapi


    【解决方案1】:

    属性路由中,您应该将控制器路由更改为[Route("api")],以接受来自https://example.com/api的所有调用。

    注意:它会影响 Reports 控制器内的所有路由。

    [Route("api")]
    public class ReportsController : ApiController
    

    然后用如下的路由属性装饰你的动作:

    [Route("{id}/[controller]/[action]")]
    

    这样您就可以使用https://example.com/api/435ABC/Reports/EndOfYear 调用您的操作方法。

    基于约定的路由中,您应该只在 UseMvc 方法中添加路由,并从控制器和操作中删除 Route 属性:

    app.UseMvc(routes =>
    {
        routes.MapRoute(name: "default", template: "api/{controller=Home}/{action=Index}"); // this line specifies default route
        routes.MapRoute(name: "Reports", template: "api/{id}/{controller=Reports}/{action=EndOfYear}"); // this line specifies your custom route
    });
    

    【讨论】:

    • 我收到以下错误:InvalidOperationException: The constraint entry 'id' - 'string' on the route 'api/{id:string}/{controller=Reports}/{action=EndOfYear}' “DefaultInlineConstraintResolver”类型的约束解析器无法解析。
    • @Brian 我的错,你不需要在路由约束中包含string。这是我的目标框架:<TargetFramework>netcoreapp2.2</TargetFramework>,它工作正常。 Here 是我所做的。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2020-12-07
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多