Kay Lamerigts
Kay Lamerigts

Reputation: 722

ASP owin somehow overrides CORS header, where can I disable this?

In the options response from my API I see this:

Access-Control-Allow-Origin:http://localhost:19600

What I want is CORS all enabled so:

Access-Control-Allow-Origin:*

I should note that it did work, and suddenly stopped working. But I dont know why.

In my OWIN startup configuration:

app.UseCors(CorsOptions.AllowAll);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);

Someone suggested in another thread that putting app.UseCors(CorsOptions.AllowAll); first would help, but it did not.

I found out that there is a way to create custom headers in Web.config at <system.webServer><httpProtocol><customHeaders>.

I tried adding the line <add name="Access-Control-Allow-Origin" value="*" /> but this resulted in two headers and was not accepted by the browser. Removing by <remove name="Access-Control-Allow-Origin"/> had no effect (neither in combination with adding).

Is there any other place where the header can be set that I am overlooking?

Upvotes: 1

Views: 146

Answers (1)

Kay Lamerigts
Kay Lamerigts

Reputation: 722

I managed to find a workaround.

I don't know the implications of this, but it works

Add this to the OWIN Config

private static void ConfigureCORSHeader(IAppBuilder app)
{
    app.Use(async (context, next) =>
    {
        var req = context.Request;
        var res = context.Response;

        res.Headers.Set("Access-Control-Allow-Origin", "*");

        if (req.Method == "OPTIONS")
        {
            res.StatusCode = 200;
            res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST", "DELETE");
            res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-headers", "authorization", "content-type");

            return;
        }

        await next();
    });
}

Upvotes: 1

Related Questions