0

I have enabled CORS in web api and i am able to catch error in jquery ajax call with correct status code when unauthorized request are made. But i find that if method with some name is not exist in controller than i am not able to catch 404 error in ajax call. Following errors are returned

OPTIONS "{url}" 404 (Not Found) jquery.js:9666 XMLHttpRequest cannot load {url}. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I think its problem with cors which is not adding headers when method is not exist. Is there any way to resolve this issue?

Sandeep
  • 33
  • 1
  • 6

1 Answers1

0

finally got solution after searching on net and get solution form following question on stackoverflow:

How to catch forms authorization error in Web API in ASP.NET MVC4

I have added one delegating handler which add headers if they are not exist to response. for example case when method is not exist or any of the required parameter is missing in request at that time Web API CORS support is not adding headers so Access-Control-Allow-Origin error received on client:

public class ResponseHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (!response.Headers.Contains("Access-Control-Allow-Headers") && !response.Headers.Contains("Access-Control-Allow-Origin"))
        {
            response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,authorization,content-type");
            response.Headers.Add("Access-Control-Allow-Origin", "*");
        }

        return response;
    }
}
Community
  • 1
  • 1
Sandeep
  • 33
  • 1
  • 6