ASP.Net核心 - 从中​​间件获取routetemplate值

时间:2017-02-22 00:24:52

标签: asp.net-core

我为API的每个请求都调用了一个中间件。我想记录路由模板以及来自此中间件的请求的持续时间。如何在我的中间件代码中获取路由模板?路线模板类似于“/ products / {productId}”。

3 个答案:

答案 0 :(得分:2)

从自定义中间件获取路由数据并不容易,因为它是由MVC中间件创建的,这通常恰好是在ASP.NET Core管道中执行的最后一个中间件。

如果您想在中间件中记录请求和响应,如下所示

_ctx = db

但是,如果你真的对路由数据感兴趣,那么实现get routes miidleware here

就有很好的答案。

其他替代方法是使用Action Filters进行请求/响应记录。

答案 1 :(得分:2)

以下是我如何使用它。我在我的过滤器OnActionExecuting方法中获取路由模板并将其添加到HttpContext。后来我从我的中间件里面的HttpContext访问它,因为我可以在中间件中访问HttpContext。

public class LogActionFilter : IActionFilter
    {
        public LogActionFilter()
        {
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Items.Add("RouteTemplate", context.ActionDescriptor.AttributeRouteInfo.Template);
        }
    }

答案 2 :(得分:0)

通过使用中间件中的ControllerActionDescriptor获取context,您实际上可以使用ASP.NET Core 3.0+轻松地实现这一目标:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    Endpoint endpointBeingHit = context.Features.Get<IEndpointFeature>()?.Endpoint;
    ControllerActionDescriptor actionDescriptor = endpointBeingHit?.Metadata?.GetMetadata<ControllerActionDescriptor>();

    this.logger.LogInformation(
        "Matched route template '{template}'",
        actionDescriptor?.AttributeRouteInfo.Template);

    await next();
}