Reputation: 279
I have used two project for my site. One for Mvc project and Api project. I have added below code in web.config file which is in Api project,
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Action method as below which is in Api project,
[HttpPost]
[Route("api/ajaxapi/caselistmethod")]
public List<CaseValues> AjaxCaseListMethod()
{
List<CaseValues> caseList = new List<CaseValues>();
return caseList;
}
and ajax call as below which is in Mvc project,
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/caselistmethod",
beforeSend: function (request) {
request.setRequestHeader("Authorization", getCookie("Token"));
},
success: function (response) {
}
});
But yet showing errors as below,
OPTIONS http://localhost:55016/api/ajaxapi/caselistmethod 405 (Method Not Allowed) XMLHttpRequest cannot load http://localhost:55016/api/ajaxapi/caselistmethod. Response for preflight has invalid HTTP status code 405
but without Header its working fine. I need to pass header also. So please give any suggestion.
Thanks...
Upvotes: 5
Views: 718
Reputation: 100527
Options method needs to be enabled for "options" pre-flight request to succeed, which in turn required to send authorization header.
It is not clear how you are enabling headers in the Web.Config or what you using to host your service so it is hard to suggest exact solution. If you are using IIS check out - enabling cross-origin resource sharing on IIS7 to make sure OPTIONS is not blocked by IIS. You may need to remove existing handlers or enable OPTIONS.
Alternatively you can use EnableCors attribute on the method to allow "options" be enabled for that route.
Upvotes: 3
Reputation: 2466
Chrome will send a preflight request (OPTIONS
method) to look for CORS headers and then send the POST request.
But you are not allowing OPTION
methods.
Try
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Upvotes: 1