CAlex
CAlex

Reputation: 1140

Server not adding Access-Control-Allow-Origin response header to 400 error response

I have been struggling with this issue for a while now. I have middle-ware on my .NET Core web API that will send a user friendly error message based on the error code returned by my SQL Server.

This works perfectly in Postman and when I disable same origin policy for Chrome From Here

So this is pretty solid evidence that it is a CORS issue. After going through many posts on issues, I still have not been able to solve the problem.

QUESTION:

If I add the Allow-Control-Allow-Origin extension in Chrome here, everything works as expected. Are all users of my application going to need this installed on their browsers to receive proper errors on the front-end? This is my biggest concern. Here is my configuration below:

Policy in Web API Startup

app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

I have it registered before MVC

services.AddCors();
services.AddMvc();

This is my method in Angular

  addNewPeopleCategory(
    personCategory: CreatePeopleCategory
  ): Observable<CreatePeopleCategory> {
    return this.http
      .post<CreatePeopleCategory>(this.url + "/create", personCategory)
      .pipe(catchError(this.handleErrorUpdate.bind(this)));
  }

This is my Error Handling method in Angular

 private handleErrorUpdate(errorResponse: HttpErrorResponse) {
    if (errorResponse.error instanceof ErrorEvent) {
      console.log("Client Side Error: ", errorResponse.error.message);
    } else {
      console.log("Server Side Error: ", errorResponse);
    }

    this.openSnackbar(errorResponse.error);
    return throwError(
      "There is an issue with the service. Please try again later.
    );
  }

When CORS are not disabled

enter image description here

When CORS are disabled in Chrome

enter image description here

Upvotes: 0

Views: 758

Answers (1)

CAlex
CAlex

Reputation: 1140

The issue was not with the way I was handling CORS on the server, but rather with the middleware I have been using for error handling.

I followed this tutorial here and it works quite well. The issue was this line in the middleware class itself:

context.Response.Clear();

Removing this line immediately fixed my CORS issues. Someone who commented at the bottom of the post tipped me off about it. From what I am gathering, this line would clear the CORS headers from the response, and then re-assign my specified status code and content type.

You will want to leave everything else in the class the same.

Upvotes: 1

Related Questions