AlexanderM
AlexanderM

Reputation: 1683

CORS errors on PUT request between Angular 4 app and MVC WebAPI

I am trying to figure out what is causing the issues between my angular applications and MVC web API application.

In my webapiconfig.cs I am enabling CORS as follows:

var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
corsAttr.SupportsCredentials = true;

// Enable CORS Globally 
config.EnableCors(corsAttr);

I am performing the PUT request using something like:

updateExchange(exchange: IOrder): Observable<IOrder> {
  return this._http.put<IOrder>(this._orderServiceUrl + '/' + order.Id, order)
    .do(this.handleSuccessResponse)
    .catch(this.handleErrorResponse);
}

I'm not really sure if this matters but in my requests I am sometimes returning different status codes based on the error.

Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I am getting back a successful response but in the response headers, I do not see any CORS headers:

    Cache-Control:private
    Date:Mon, 02 Oct 2017 15:37:31 GMT
    Server:Microsoft-IIS/10.0
    Transfer-Encoding:chunked
    X-AspNet-Version:4.0.30319
    X-Powered-By:ASP.NET
    X-SourceFiles:=?UTF-8?<something>

Any suggestion on what should I do to get this working?

Upvotes: 1

Views: 831

Answers (2)

Zvi Redler
Zvi Redler

Reputation: 1758

Search your code, maybe you add the header twice, that what was happend to me...

We did

var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
corsAttr.SupportsCredentials = true;
config.EnableCors(corsAttr);

And in another place:

        With filterContext.RequestContext.HttpContext.Response
            .AddHeader("Access-Control-Allow-Origin", "*");
            .AddHeader("Access-Control-Allow-Methods", "*");
            .AddHeader("Access-Control-Allow-Headers", "*");
        End With

Upvotes: 0

FussinHussin
FussinHussin

Reputation: 1814

Response should only have the accepted headers in Access-Control-Allow-Headers, don't use wildcard. There are security concerns to this, and that's why you are getting the error.

refer to the answer in this post for more information on why this is a bad practice. It is an angular.js post, but the CORS aspect applies

Upvotes: 1

Related Questions