【发布时间】:2018-02-20 14:24:06
【问题描述】:
更新:现在我对错误有了更好的理解。我面临这里解释的错误:https://stackoverflow.com/a/20035319/3021830。这就是我现在应该解决的问题。
我使用 ASP.NET WebAPI 创建了 REST API。它托管在http://localhost:54700/。我还有一个带有路由“api/RefData”的GET方法,所以基本上我需要调用http://localhost:54700/api/RefData。 IT 也标有AllowAnonymous 属性
当我从 PostMan 进行 GET 调用时,一切似乎都正常。 但是我尝试从我的 ASP.NET MVC 应用程序中调用它,无论是从服务器还是客户端我都无法得到任何结果。
我的服务器端代码是:
private static HttpClient _client;
private static HttpClient Client
{
get
{
if (_client == null)
{
_client = new HttpClient();
_client.BaseAddress = new Uri("http://localhost:54700/");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
return _client;
}
}
internal List<HeardAbout> HeardAbouts
{
get
{
if (System.Web.HttpContext.Current.Session["refData"] == null)
{
GetRefData().Wait();
}
return System.Web.HttpContext.Current.Session["refData"] as List<RefData>;
}
}
private async Task<List<RefData>> GetRefData()
{
try
{
List<RefData> has = new List<RefData>();
// The following line is where the code leaves debugging
HttpResponseMessage response = await Client.GetAsync("api/RefData");
if (response.IsSuccessStatusCode)
{
has = await response.Content.ReadAsAsync<List<RefData>>();
System.Web.HttpContext.Current.Session["refData"] = has;
}
return has;
}
catch (Exception ex)
{
throw;
}
}
我的客户端代码是:
$.ajax({
type: "GET",
url: "http://localhost:54700/api/RefData",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (callback)
callback(response.d);
},
error: function (response) {
if (callback)
error(response.d);
},
});
服务器端代码到达注释行。然后离开调试。我用 try-catch 块包装了代码,但它也没有引发异常。
客户端代码出错,statusText“错误”。
这些代码有什么问题,我该如何解决?
提前致谢。
【问题讨论】:
-
你的服务器端httpclient返回的状态码是什么?
-
在客户端代码中尝试方法:'GET'而不是类型
-
这没有意义,但据我所知 response.statusCode 返回函数 (e){var t;if(e)if(2>b)for(t in e)m[ t]=[m[t],e[t]];else C.always(e[C.status]);return this}
-
我想我搞砸了。我的 WebAPI 和我的网站在不同的域上运行,我收到“XMLHttpRequest 无法加载请求的资源上不存在'Access-Control-Allow-Origin' 标头。因此不允许访问来源'localhost:55973'。”错误。我认为这是我需要解决的问题。
-
寻找 CORS,我遇到了类似的问题并启用了 cors 并且工作正常。
标签: c# ajax rest asp.net-web-api cors