Search code examples
ajaxrestmodel-view-controllerasp.net-web-apiwcf-rest

Rest API - 405 method not allowed


I am new to the Rest API. I am trying to call cross domain rest API from my application. Here is my code -

 $.ajax({
            type: "GET",
            async: false,
            url: 'http://xx.xxx.xxx.xx:9003/GetProjectList',
            contentType: "application/json",
            dataType: "json",
            traditional: true,
            CrossDomain: true,
            data: {
                StartDate: '2016-12-20',
                EndDate: '2017-01-10'
            },
            success: function (data) {
                alert("Success");
                alert(data);

            },

            error: function (xhr, textStatus, errorThrown) {
                alert("Failed");
                alert(xhr);
                alert(textStatus);
                alert(errorThrown);

            }
        }); 

But i am getting the error as

OPTIONS http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10 405 (Method Not Allowed)

XMLHttpRequest cannot load http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64207' is therefore not allowed access. The response had HTTP status code 405.

Am i missing anything here? any code or configuration?

If i hit that URL directly from browser or Postman, its working fine. But its not working from the application.


Solution

  • The problem is about CORS(Cross-Origin Requests). You have to enable CORS for solve the problem.

    Download with Nuget Package

    Install-Package Microsoft.AspNet.WebApi.Cors
    

    You should add some code in WebApiConfig.cs

    var corsAttr = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(corsAttr);
    

    More Information you should take a look: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api