aspnet / AspNetWebStack

ASP.NET MVC 5.x, Web API 2.x, and Web Pages 3.x (not ASP.NET Core)
Other
858 stars 354 forks source link

When an exception occurred, response doesn't have any origin CORS headers by using custom ExceptionHandler in WebApi with CORS enabled #266

Closed andy26500 closed 3 years ago

andy26500 commented 4 years ago

I enable CORS and replace exception handler with my handler for custom error response in WebApiConfig.cs.

config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // for tesing purpose
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

In my html page, I setup "application/json" as contentType of jquery ajax settings. Browser always send preflight request and get success response with CORS header.

image

The next request for execute code, I except get a custom error message like:

{
    "LogId": 123,
    "Message": "Not Implemented."
}

But I get a response without CORS header and I can't access any content in response. image

Browser also shows this response has been blocked by CORS policy.

image

image

If I comment out code config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());, I will response with CORS header and full stacktrace as content.

Please refer Demo code.

rubens-farias commented 4 years ago

I enable CORS and replace exception handler with my handler for custom error response in WebApiConfig.cs.

It seems like you'll need to also override the ShouldHandle to always return true, per https://stackoverflow.com/a/24634485/113794

mkArtakMSFT commented 3 years ago

Thanks for your help here, @rubens-farias. Closing as the question has been answered.