title: The session cannot be established after the response has started
body: <p>I saw this error in my logs, but I can't figure out how to reproduce it. It does not occur regularly. </p>
  
  <p><strong>Exception Message:</strong> The session cannot be established after the response has started. 
  <strong>Stack trace:</strong> </p>
  
  <p><em>at Microsoft.AspNetCore.Session.DistributedSession.Set(String key, Byte[] value)</em></p>
  
  <p>CustomMiddleware.cs:</p>
  
  <pre><code>    public async Task Invoke(HttpContext context, AlertWriter alertWriter, AlertReader alertReader)
      {
          var sessionAlerts = context.Session.GetString(AlertKey);
  
          if (!string.IsNullOrWhiteSpace(sessionAlerts))
          {
              var alerts = JsonConvert.DeserializeObject&lt;List&lt;Alert&gt;&gt;(sessionAlerts);
              alertReader.Initialize(alerts);
  
              context.Session.Remove(AlertKey);
          }
  
          await _next.Invoke(context);
  
          if (context.Response.StatusCode &gt;= 300 &amp;&amp; context.Response.StatusCode &lt; 400)
          {
              alertWriter.Alerts = alertWriter.Alerts.Union(alertReader).ToList();
          }
  
          var serializedAlerts = JsonConvert.SerializeObject(alertWriter.Alerts);
  
          //ERROR IS HERE
          context.Session.SetString(AlertKey, serializedAlerts);
      }
  </code></pre>
  
  <p>In Startup.cs, <code>app.UseSession();</code> is the first app.Use... that I call. 
  <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state" rel="nofollow noreferrer">Documentation</a> says that this error will occur if you <em>"attempt to create a new Session (i.e. no session cookie has been created yet) after you have already begun writing to the Response stream"</em>.</p>
  
  <p>How can I avoid this error? Seems like if I try to access the session in any custom middleware, I'll have to check if the .AspNetCore.Session cookie exists? </p>