title: Code correctly returning a 401 unauthorised error in ASP.Net Core RC2 now incorrectly returns a 500 error
body: <p>We have an ASP.Net Core web service using Azure AD B2C for bearer token authentication. Our iOS client makes an API request and if the ASP.Net Core server returns a 401 Unauthorised error with the term "SecurityTokenExpiredException" in the body then the client refreshes its token and tries again.</p>
  
  <p>This works great under ASP.Net Core RC2 but now that we have moved to the release version we cannot deploy our server without breaking our clients because the server no longer correctly returns a 401 Unauthorised error and instead returns a 500 error.</p>
  
  <p>The code that sets up the 401 is in Startup.cs</p>
  
  <pre class="lang-csharp prettyprint-override"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      app.Use(async (context, next) =&gt;
      {
          try
          {
              await next();
          }
          catch (Exception ex)
          {
              if (context.Response.HasStarted)
              {
                  throw;
              }
  
              int statusCode = 500;
  
              if (ex is SecurityTokenInvalidSignatureException ||
                  ex is SecurityTokenInvalidLifetimeException ||
                  ex is SecurityTokenExpiredException)
              {
                  statusCode = 401;
              }
              else if (ex is ResourceNotAuthorizedException)
              {
                  statusCode = 403;
              }
              else if (ex is ResourceNotFoundException || ex is UserDoesNotExistException)
              {
                  statusCode = 404;
              }
  
              context.Response.StatusCode = statusCode;
              await context.Response.WriteAsync(new ExceptionResponse(statusCode, ex).ToString());
          }
      });
      //[...]
  </code></pre>
  
  <p>(N.B. If I step through this code in the debugger each line executes, the local variable <code>statusCode</code> is correctly set to 401, and those final two lines are run, but the error sent back by ASP.Net Core to the client is 500 and not 401.)</p>
  
  <p>Has something changed going from RC2 to the ASP.Net Core release that would render this code incorrect? What is the new way of writing this?</p>