Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Header can't pass in ajax using cross domain

Tags:

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...

like image 614
Arun D Avatar asked Jun 12 '17 14:06

Arun D


1 Answers

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.

like image 98
Alexei Levenkov Avatar answered Oct 11 '22 12:10

Alexei Levenkov