1
votes

I've enabled CORS for my web api project before deploying it to local IIS. However, when I try to call a controller method from Angular, I am getting the following error:

SEC7128: Multiple Access-Control-Allow-Origin headers are not allowed for CORS response.

To enable CORS on my web api, I've added this line of code to WebApi.config:

config.EnableCors();

I've also added this attribute to my controller class:

[EnableCors(origins: "http://localhost:53720", headers: "*", methods: "*")]
3

3 Answers

0
votes

"*" as Access-Control-Allow-Origin doesn't work well for all browsers. To be able to call Web API from any site, one can take Origin HTTP request header as a single allowed origin, copying it into Access-Control-Allow-Origin. This can be done by following OWIN middleware:

class CORSAnyOriginMiddleware : OwinMiddleware
{
    const string OriginHeader = "Origin";
    const string AllowOriginHeader = "Access-Control-Allow-Origin";

    public CORSAnyOriginMiddleware(OwinMiddleware next) : base(next)
    { }

    public override async Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);

        if (context.Response?.Headers?.ContainsKey(AllowOriginHeader) ?? false &&
            (context.Request?.Headers?.ContainsKey(OriginHeader) ?? false))
            context.Response.Headers[AllowOriginHeader] =
                context.Request.Headers[OriginHeader];
    }
}

Sample usage (inside Startup.Configuration(IAppBuilder appBuilder)):

appBuilder.Use<CORSAnyOriginMiddleware>();
0
votes

Like error says that header is not allowed. To allow that header you should add header:

Access-Control-Allow-Headers

In which you need to add value:

Access-Control-Allow-Origin

Beside that you also need to add other header names, which you want to use in your responses.

E.g. If you want to use MyAwesomeHeader header:
{"Access-Control-Allow-Headers": "Access-Control-Allow-Origin, MyAwesomeHeader"}

0
votes

I managed to solve it by removing this line from my web.config:

<add name="Access-Control-Allow-Origin" value="*" />