Trying to set up CORS with authentication. I have a Web API site up at http://localhost:61000 and a consuming web application up at http://localhost:62000. In the Web API S
I was having this same issue on a Web API project using OWIN middleware, where a wrong package version was causing errors on the API side (hidden on the client side because CORS headers were stripped on the response, which obscured the original error). I implemented a similar solution to yours, sharing here because I could not find any similar example using OWIN on the web:
using System;
using System.Linq;
using System.Threading.Tasks;
using Owin;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
namespace App_Server
{
using AppFunc = Func, Task>;
partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.Use(new Func(RetainHeaders));
....
(other startup tasks)
}
private AppFunc RetainHeaders(AppFunc next)
{
AppFunc appFunc = async (IDictionary context) =>
{
IOwinContext httpContext = new OwinContext(context);
var corsHeaders = new HeaderDictionary(new Dictionary());
foreach (var pair in httpContext.Response.Headers)
{
if (!pair.Key.ToLower().StartsWith("access-control-")) { continue; } //not a CORS header
corsHeaders[pair.Key] = pair.Value.First();
}
httpContext.Response.OnSendingHeaders(o =>
{
var localcontext = new OwinContext((IDictionary)o);
var headers = localcontext.Response.Headers;
//make sure headers are present, and if not, add them back
foreach (var pair in corsHeaders)
{
if (headers.ContainsKey(pair.Key)) { continue; }
headers.Add(pair.Key, pair.Value);
}
}, context);
await next.Invoke(context);
};
return appFunc;
}
}
This was a quite a process to work out given how poorly documented the OWIN packages are for .Net, so I hope it helps someone else who comes across it looking for a solution.