title: ASP NET Core: Overwrite Username of HttpContext
body: <p>Is there a way to set the user name in an ASP NET Core application via Middleware?</p>
  
  <p>I created a <code>AnonymousUserMiddleware</code>:</p>
  
  <pre><code>    public AnonymousUserMiddleware(RequestDelegate next, HttpContextCurrentClaimsPrincipalAccessor currentClaimsPrincipalAccessor, ILogger&lt;AnonymousUserMiddleware&gt; logger)
      {
          _next = next;
          _currentClaimsPrincipalAccessor = currentClaimsPrincipalAccessor;
          _logger = logger;
      }
  
      public async Task Invoke(HttpContext context)
      {
          try
          {
              _currentClaimsPrincipalAccessor?.Current?.Identity?.Name = "anonymous";
              await _next.Invoke(context);
          }
          catch (Exception ex)
          {
              _logger.LogError(1, ex, "Exception");
              throw ex;
          }
      }
  </code></pre>
  
  <p>But this doesn't work, because <code>Name</code> is a readonly field.</p>
  
  <p>I want to call this in the <code>Startup.cs</code> when in Developer-Mode so that the user name is always "anonymous" during a request.</p>
  
  <p>Is there a way to accomplish this?</p>