2017-08-28 243 views
1

为了将请求数据记录到我们的数据库中,我在我的项目中编写了一个中间件类。在中间件中读取控制器和操作名称.Net 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 
    }  
} 
+0

[路由控制器和行动在中间件(https://stackoverflow.com/questions/39335824/route-controller-and-action-in-middleware)的可能的复制 – CodeCaster

+1

[如何获取当前ASP使用反射或其他准确的方法控制器内的.NET核心控制器方法名称](https://stackoverflow.com/questions/35534337/how-to-get-the-current-asp-net-core-controller-method-name内部控制器) – CodeCaster

+0

我知道但可能太老了? – Metalex

回答

1

控制器和操作数据都可以通过过滤器,这样我实现了这种方式。控制器和操作数据在ActionExecutingContext对象中可用。

public class AsyncActionFilter : IAsyncActionFilter 
{ 
    public AsyncActionFilter(IEntityContext entityContext) 
    { 
     _entityContext = entityContext; 
    } 

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 
    { 
      //Handle the request 
      await next(); 
    } 
} 
相关问题