Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Controller and Action name in middleware .Net Core

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     }        } 
like image 885
Metalex Avatar asked Aug 28 '17 14:08

Metalex


2 Answers

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().
like image 190
Ganesh Avatar answered Oct 14 '22 07:10

Ganesh


Adding to Ganesh's answer I'd like to add a few conditions.

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

Otherwise GetEndpoint() returns null.

like image 32
Matthias Schuchardt Avatar answered Oct 14 '22 07:10

Matthias Schuchardt