【问题标题】:How can I setup attribute based routing in ASP.NET Core 3.0如何在 ASP.NET Core 3.0 中设置基于属性的路由
【发布时间】:2020-03-16 16:39:29
【问题描述】:

在我的 startup.cs 类中,我有:

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

我的控制器目前看起来像这样:

[Microsoft.AspNetCore.Components.Route("api/my-test")]
public class MyTestController : ControllerBase
{
    [HttpGet]
    [Route("{confirmationCode}")]
    public async Task<IActionResult> Get(string confirmationCode)
    {
        return Ok($"The confirmation code is: {confirmationCode}");
    }
}

如何在 MyTestController 上调用 Get 操作,并从如下所示的路由 URL 访问作为 URL 的一部分传入的确认代码: /api/my-test/abc123

【问题讨论】:

    标签: asp.net .net asp.net-mvc asp.net-web-api .net-core


    【解决方案1】:

    经过多次尝试,我自己想出了解决方案:

    [Route("api/my-test")] // <-- this Route is from Microsoft.AspNetCore.Mvc.RouteAttribute
    public class MyTestController : ControllerBase
    {
        // GET api/my-test/abc123
        [HttpGet("{confirmationCode}")] // <-- instead of Route, you tack on the rest of your route pattern into the HttpGet attribute (or other verbs depending on your code)
        public async Task<IActionResult> Get(string confirmationCode)
        {
            return Ok($"The confirmation code is: {confirmationCode}");
        }
    }
    

    以下是两个变化/差异:

    1. 我的非工作代码中的“Route”元素来自“Microsoft.AspNetCore.Components”。正确的命名空间是“Microsoft.AspNetCore.Mvc.RouteAttribute”。
    2. 不要在操作方法级别使用“路由”,而是将路由模式的其余部分添加到 HTTP 动词修饰中。在我上面的示例中,我将它添加到我在方法上使用的 HttpGet 装饰器中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2020-05-01
      • 2020-10-07
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多