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 } }
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.
AddControllers()
instead of AddMvc()
)UseRouting()
and UseEndpoints()
.Adding to Ganesh's answer I'd like to add a few conditions.
AddControllers()
instead of AddMvc()
)UseRouting()
and UseEndpoints()
.Otherwise GetEndpoint()
returns null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With