5

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

Arun D
  • 279
  • 3
  • 18

2 Answers2

3

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

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
S.Dav
  • 2,436
  • 16
  • 22
  • 1
    I don't believe `Access-Control-Allow-Methods` impacts 405 from OPTIONS request itself. You should not need to add "OPTIONS" to this list as one unlikely to make OPTIONS cross-domain call (pre-flight OPTIONS call is not considered "cross-domain" by browser as it is made by browser itself and not client's code) – Alexei Levenkov Jun 12 '17 at 14:56
  • Nothing happen after allowing OPTIONS method also. @S.Dev – Arun D Jun 13 '17 at 05:38