Read Controller and Action name in middleware .Net Core

Metalex picture Metalex · Aug 28, 2017 · Viewed 8.7k times · Source

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?

I have something like this:

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
    }       
}

Answer

Ganesh picture Ganesh · May 19, 2020

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);
}

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

  • Enable endpoint routing (AddControllers() instead of AddMvc())
  • Call your middleware between UseRouting() and UseEndpoints().