我是 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/