ajax - Rest API - 405 方法不允许

标签 ajax rest model-view-controller asp.net-web-api wcf-rest

我是 Rest API 的新手。我正在尝试从我的应用程序调用跨域 REST API。 这是我的代码 -

 $.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);

            }
        }); 

但是我收到的错误是

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.

我在这里错过了什么吗?有代码或配置吗?

如果我直接从浏览器或 postman 点击该 URL,它工作正常。但它在应用程序中不起作用。

最佳答案

问题与 CORS(跨源请求)有关。您必须启用 CORS 才能解决问题。

使用Nuget包下载

Install-Package Microsoft.AspNet.WebApi.Cors

您应该在 WebApiConfig.cs 中添加一些代码

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

您应该查看的更多信息: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

关于ajax - Rest API - 405 方法不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613291/

相关文章:

jquery - 防止并发 ajax 请求

asp.net-mvc - 如何使用 MVC 和 jQuery AJAX 传递对象?

java - 如何使用 javascript 从 HTML 调用服务器端 java 方法?

c# - SelectedItem 在 ASPNET.MVC 的 SelectList 中没有被记住

jquery - 如何添加带有甜蜜警报的 Ajax 调用

java - 创建新资源时出现 400 错误的 Dropwizard 示例

java - 使用 JSON 传递对象和整数

android - 写入远程数据库操作可以在单独的异步线程中进行吗? (德尔福)

php - 我应该访问模型中的 POST 参数还是作为方法参数从 Controller 传递?

Qt 模型/ View : how to handle underlying data properly