ASP.NET Core CORS request blocked; why doesn't my API apply the right headers?
For ASP.NET Core 2.1 and earlier:
It seems there was an error in my code, but I got the obscure error noted instead of getting an ASP.NET-generated error page. It turns out that the CORS headers are indeed properly applied at first, but then they are stripped off any ASP.NET middleware-generated errors. See also https://github.com/aspnet/Home/issues/2378 .
I used that link to figure out this class
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace MySite.Web.Middleware
{
/// <summary>
/// Reinstates CORS headers whenever an error occurs.
/// </summary>
/// <remarks>ASP.NET strips off CORS on errors; this overcomes this issue,
/// explained and worked around at https://github.com/aspnet/Home/issues/2378 </remarks>
public class MaintainCorsHeadersMiddleware
{
public MaintainCorsHeadersMiddleware(RequestDelegate next)
{
_next = next;
}
private readonly RequestDelegate _next;
public async Task Invoke(HttpContext httpContext)
{
// Find and hold onto any CORS related headers ...
var corsHeaders = new HeaderDictionary();
foreach (var pair in httpContext.Response.Headers)
{
if (!pair.Key.ToLower().StartsWith("access-control-")) { continue; } // Not CORS related
corsHeaders[pair.Key] = pair.Value;
}
// Bind to the OnStarting event so that we can make sure these CORS headers are still included going to the client
httpContext.Response.OnStarting(o => {
var ctx = (HttpContext)o;
var headers = ctx.Response.Headers;
// Ensure all CORS headers remain or else add them back in ...
foreach (var pair in corsHeaders)
{
if (headers.ContainsKey(pair.Key)) { continue; } // Still there!
headers.Add(pair.Key, pair.Value);
}
return Task.CompletedTask;
}, httpContext);
// Call the pipeline ...
await _next(httpContext);
}
}
}
And then I added it to my site configuration in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(...);
app.UseMiddleware<MaintainCorsHeadersMiddleware>();
...
app.UseMvc();
}
ASP.NET Core 2.2.0 Answer
This issue is now fixed. CORS headers are now returned even when exceptions are thrown and a 500 response is returned.
ASP.NET Core <= 2.1.0 Answer
CORS Headers were stripped from the response when an exception is thrown and a 500 response is returned.