【问题标题】:How to get value of Route attribute in dotNet Core如何在 dotNet Core 中获取 Route 属性的值
【发布时间】:2018-08-17 21:12:57
【问题描述】:

我有一个这样启动的控制器

[Route("api/v1/[controller]")]
public class ReportController : ControllerBase

我想知道是否有办法在其中一种方法中获取“api/v1/report”。

“Request.Path”返回它,但如果我已经为方法添加了路由,例如

[HttpGet("store/{id}")]

它返回添加到它上面的内容,我想可靠地获取基本路由,而无需进行字符串操作。

【问题讨论】:

  • 控制器上的路由在技术上不是基本路由。整个东西放在一起存储在路由表中。
  • 注意,我知道基本路由是协议/域等。只是不确定如何参考第一部分和第二部分

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


【解决方案1】:
this.GetType().CustomAttributes
            .FirstOrDefault(r => r.AttributeType == typeof(RouteAttribute))
            .ConstructorArguments[0].Value.ToString()
            .Replace("[controller]",(string)this.RouteData.Values["controller"]);

我能够通过四处挖掘找到它,但我希望有一种更清洁的方法来获得它。这将返回一个字符串“api/v1/report”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多