Ajax Rest API-不允许使用405方法
我不熟悉RESTAPI。我正在尝试从我的应用程序调用跨域RESTAPI。 这是我的密码-Ajax Rest API-不允许使用405方法,ajax,rest,model-view-controller,asp.net-web-api,wcf-rest,Ajax,Rest,Model View Controller,Asp.net Web Api,Wcf Rest,我不熟悉RESTAPI。我正在尝试从我的应用程序调用跨域RESTAPI。 这是我的密码- $.ajax({ type: "GET", async: false, url: 'http://xx.xxx.xxx.xx:9003/GetProjectList', contentType: "application/json", dataType: "json",
$.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.
我有什么遗漏吗?有代码或配置吗
如果我直接从浏览器或邮递员那里点击那个URL,它就可以正常工作了。但是它不能从应用程序中工作。我认为问题是CORS问题(有时405也意味着您使用错误的HTTP谓词调用API)。。但是读取您的异常看起来像是CORS问题。。试试这个:
using Goocity.API;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
[assembly: OwinStartup("API", typeof(Goocity.API.Startup))]
namespace Goocity.API
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
#region TO UNCOMMENT WHEN IS IN PRODUCTION
//var corsPolicy = new CorsPolicy
//{
// AllowAnyMethod = true,
// AllowAnyHeader = true,
// SupportsCredentials = true,
// Origins = { "http://www.yoursite.it" }
//};
//app.UseCors(new CorsOptions
//{
// PolicyProvider = new CorsPolicyProvider
// {
// PolicyResolver = context => Task.FromResult(corsPolicy)
// }
//});
#endregion TO UNCOMMENT WHEN IS IN PRODUCTION
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
}
}
}
尝试将其放入启动文件并安装Microsoft.Owin.Cors nuget软件包问题在于Cors(跨源请求)。您必须启用CORS以解决问题
使用Nuget软件包下载
Install-Package Microsoft.AspNet.WebApi.Cors
您应该在WebApiConfig.cs中添加一些代码
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
有关更多信息,请查看:
这是基本的CORS错误。您应该在响应标头中设置所需的CORS标头。关于这一点有很多答案。顺便问一下,您的服务是web api还是wcf rest?您不应该同时添加这两个标记,您只需要允许COR。知道这一点,它并不总是有效的!为什么要在GET请求上设置内容类型?