Read Controller and Action name in middleware .Net Core

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().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)