【问题标题】:How to get URL template path in ASP.NET Core?如何在 ASP.NET Core 中获取 URL 模板路径?
【发布时间】:2019-01-02 20:31:32
【问题描述】:

我正在研究 ActionFilter,需要获取像 /api/v{version}/controllerName/actionName/{parameter} 这样的 URL 模板路径。但是,该解决方案需要是通用的,因此它支持多种 URL 模式,例如 api/v{version}/controllerName/actionName/{parameter}/otherActionName/{otherParameter}

ASP.NET Core 2.2 最新稳定版。我所拥有的是ActionExecutedContext,其中也包含HttpContext。但是,我不确定这个HttpContext 的内容,因为它包含一些响应的默认值。

    private PathString GetUrlTemplatePath(ActionExecutedContext context)
    {
        // TODO:
        return context.HttpContext.Request.Path;
    }

实际结果:/api/v1/Location/addresses/999999A1-458A-42D0-80AA-D08A3DAD8199

预期结果:/api/v{version}/location/addresses/{externalId} 其中externalId 是属性[HttpGet("addresses/{externalId}", Name = "GetAddress")] 描述的参数名称。

【问题讨论】:

  • 只是想知道您为什么需要它?
  • 建议您提供一个最小的完整示例。被问到不清楚你想要什么。
  • @DanielA.White 用于在控制器上收集 Prometheus 指标的操作过滤器。我需要这个模板路径作为指标上的标签。

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


【解决方案1】:

您可以从 ResourceFilter 中的 ActionExecutedContext 获取模板路径。如果您需要QueryString 来解决您的问题,或者Dictionary<string, object> 类型的上下文中有ActionArguments,它包含随请求传递的所有参数。

//template
string template = context.ActionDescriptor.AttributeRouteInfo.Template;;

//arguments
IDictionary<string, object> arguments = context.ActionArguments;

//query string
string queryString= context.HttpContext.Request.QueryString.Value;

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    您可以从context.ActionDescriptor.AttributeRouteInfo 获得其中的一部分。我不能 100% 确定这是完整的还是只是其中的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多