title: ASP.NET Core Middleware Passing Parameters to Controllers
body: <p>I am using <code>ASP.NET Core Web API</code>, where I have Multiple independent web api projects. Before executing any of the controllers' actions, I have to check if the the logged in user is already impersonating other user (which i can get from <code>DB</code>) and can pass the impersonated user <code>Id</code> to the <code>actions</code>.</p>
  
  <p>Since this is a piece of code that gonna be reused, I thought I can use a middleware so:</p>
  
  <ul>
  <li>I can get the initial user login from request header</li>
  <li>Get the impesonated User Id if any</li>
  <li><strong>Inject that ID in the request pipeline to make it available to the api being called</strong></li>
  </ul>
  
  
  
  <pre><code>public class GetImpersonatorMiddleware
  {
      private readonly RequestDelegate _next;
      private IImpersonatorRepo _repo { get; set; }
  
      public GetImpersonatorMiddleware(RequestDelegate next, IImpersonatorRepo imperRepo)
      {
          _next = next;
          _repo = imperRepo;
      }
      public async Task Invoke(HttpContext context)
      {
          //get user id from identity Token
          var userId = 1;
  
          int impersonatedUserID = _repo.GetImpesonator(userId);
  
          //how to pass the impersonatedUserID so it can be picked up from controllers
          if (impersonatedUserID &gt; 0 )
              context.Request.Headers.Add("impers_id", impersonatedUserID.ToString());
  
          await _next.Invoke(context);
      }
  }
  </code></pre>
  
  <p>I found this <a href="https://stackoverflow.com/questions/39017590/is-it-possible-to-send-values-to-controller-from-middleware-in-aspnet-core-api">Question</a>, but that didn't address what I am looking for.</p>
  
  <p>How can I pass a parameter and make it available in the request pipeline? Is it Ok to pass it in the header or there is more elegant way to do this?</p>