Header cannot go through ajax using cross domain

I used two projects for my site. One for the Mvc project and the Api project. I added the code below in the web.config file, which is in the Api project,

Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Authorization 

The action method below in the Api project,

 [HttpPost] [Route("api/ajaxapi/caselistmethod")] public List<CaseValues> AjaxCaseListMethod() { List<CaseValues> caseList = new List<CaseValues>(); return caseList; } 

and ajax, as shown below, in the Mvc project,

 $.ajax({ type: "POST", url: "http://localhost:55016/api/ajaxapi/caselistmethod", beforeSend: function (request) { request.setRequestHeader("Authorization", getCookie("Token")); }, success: function (response) { } }); 

But showing errors as shown below

OPTIONS http: // localhost: 55016 / api / ajaxapi / caselistmethod 405 (method not allowed) XMLHttpRequest cannot load http: // localhost: 55016 / api / ajaxapi / caselistmethod . Preflight response has an invalid HTTP status code 405

but without a title its working tone. I also need to pass the header. Therefore, please give any suggestion.

Thanks...

+5
source share
2 answers

You must activate the options method to request a "foreground" for "options", which, in turn, was supposed to send an authorization header.

It is not clear how to include headers in Web.Config or what you use to host your service, so itโ€™s difficult to offer an exact solution. If you are using an IIS account โ€” to enable resource sharing for different sources in IIS7 to ensure that IIS settings are not blocked. You may need to remove existing handlers or enable OPTIONS.

Alternatively, you can use the EnableCors attribute for the method to enable โ€œoptionsโ€ for this route.

+3
source

Chrome will send a pre-check request ( OPTIONS method) to view the CORS headers, and then send a POST request.

But you do not allow OPTION methods.

Try

 Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS 
+1
source

Source: https://habr.com/ru/post/1268775/


All Articles