title: .NET Core MVC get route matched for logging middleware
body: <p>In my project I am logging every request using logging middleware. How can I get the route that was matched for the request for logging purposes?</p>
  
  <p>I have the full path in the request e.g. /v1/User/123</p>
  
  <p>But I want to log this: /v1/User/{id}</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  {
      var path = context.ActionDescriptor.AttributeRouteInfo.Template;
  
      await next();
  }
  </code></pre>
  
  <p>This is in my base controller, how do I get this to the logging middleware?</p>
  
  <p>Here is how I got it to the logging middleware:</p>
  
  <p>BaseController:</p>
  
  <pre><code>public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  {
      var actionPath = context.ActionDescriptor.AttributeRouteInfo.Template;
  
      HttpContext.Items.Add("ActionInfo", actionPath);
  
      await next();
  }
  </code></pre>
  
  <p>LoggingMiddleware:</p>
  
  <pre><code>var actionInfo = context.Items["ActionInfo"];
  
  if (actionInfo != null)
  {
      actionMatched = actionInfo.ToString();
  }
  </code></pre>
  
  <p>Is there a better way to do this?
  Also this only works if you are using attribute routing. How can this work if you are registering routes on startup?</p>