[jquery] jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

I am sending a post request to a RESTFUL WCF service application. I am able to successfully send a POST request through Fiddler.

However when I do this through the jQuery Ajax method the function returns the following to the Chrome Developer Console:

OPTIONS http://www.example.com/testservice/service1.svc/GetData 405 (Method Not Allowed) jquery.min.js:6

But then a second after logs:

Object {d: "You entered 10"} testpost.html:16

What this tells me is that jQuery is sending a OPTIONS request, which fails, and then sending a POST request which returns the expected data.

My jQuery Code:

$.ajax() {        
type: "POST", //GET or POST or PUT or DELETE verb 
    url: "http://www.example.com/testservice/service1.svc/GetData", // Location of the service      
    data: '{"value":"10"}', //Data sent to server
    contentType:"application/json",
    dataType: "json", //Expected data format from server    
    processdata: false,
    success: function (msg) {//On Successfull service call   
        console.log(msg);
    },
    error: function (xhr) { console.log(xhr.responseText); } // When Service call fails             
});

I am using jQuery version 2.0.2.

Any help on why this error is occurring would be a great help.

This question is related to jquery web-services rest post wcf-rest

The answer is


Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.


For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

You must add this code in global.aspx:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

This Worked for me

In Web.config add below script

_x000D_
_x000D_
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="WebDAVModule"/>
  </modules>
  <handlers accessPolicy="Read, Execute, Script">
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />

    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
         verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
         type="System.Web.Handlers.TransferRequestHandler"
         preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
 </system.webServer>
_x000D_
_x000D_
_x000D_

Also in RouteConfig.cs

Change

settings.AutoRedirectMode = RedirectMode.Permanent;

To

settings.AutoRedirectMode = RedirectMode.Off;

Hope it helps you or some one :)


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to wcf-rest

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF Cannot set content-type to 'application/json' in jQuery.ajax