读取中间件.Net Core中的Controller和Action名称 [英] Read Controller and Action name in middleware .Net Core

查看:679
本文介绍了读取中间件.Net Core中的Controller和Action名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在项目中编写一个中间件类,以便将请求数据记录到我们的数据库中.

I am writing a middleware class within my project in order to log the request data into our database.

我看不到任何简单的方法来获取控制器名称和操作?有机会轻松做到这一点吗?

I do not see any easy way to get the controller name and action ? Any chance to do this easily in core?

我有这样的东西:

public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestResponseLoggingMiddleware(RequestDelegate next)
    {
        _next = next;            
    }

    public async Task Invoke(HttpContext context)
    {        
        //handle the request
        //something like: context.GetRouteData();

        await _next(context);                 

        //handle the response
    }       
}

推荐答案

我遇到了同样的问题,这在.NetCore 3.1中对我有用:

I had the same issue and this worked for me in .NetCore 3.1:

public async Task InvokeAsync(HttpContext httpContext)
{
    var controllerActionDescriptor = httpContext
        .GetEndpoint()
        .Metadata
        .GetMetadata<ControllerActionDescriptor>();

    var controllerName = controllerActionDescriptor.ControllerName;
    var actionName = controllerActionDescriptor.ActionName;
            
    await _next(httpContext);
}

为了使 GetEndpoint()返回实际的null端点instad,必须满足以下条件.

In order for GetEndpoint() to return the actual endpoint instad of null, the following conditions have to be met.

  • 启用端点路由( AddControllers()而不是 AddMvc())
  • UseRouting() UseEndpoints()之间调用中间件.
  • Enable endpoint routing (AddControllers() instead of AddMvc())
  • Call your middleware between UseRouting() and UseEndpoints().

这篇关于读取中间件.Net Core中的Controller和Action名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆