【发布时间】:2017-02-13 03:29:03
【问题描述】:
我有一个返回字符串的 Asp.Net Core web api 方法。
[Route("GetString")]
public string GetString()
{
return "String from <b> Web </b> API";
}
该 URL 在浏览器中可以正常工作,但是,当我从 Angular 2 应用程序运行它时
getDialog(){
this.result = this.http.get(this._stringUrl1).forEach((response) => response.text);
console.log(this.result);
}
我收到以下错误消息:
XMLHttpRequest cannot load http://localhost:49596/Content/GetString. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
如果我调用返回 HttpResponseMessage 的 web api 方法,我会得到相同的响应。
[Route("GetHttpResponseMessage")]
public HttpResponseMessage GetString2()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("HttpResponseMessage from Web API 2", Encoding.UTF8, "Text/txt");
return response;
}
这是我的第一个 Angular 应用程序,所以我不确定我的 angular2 代码是否正确。任何帮助表示赞赏。
【问题讨论】:
-
这不是你的 Angular 代码的问题;你需要在 API 端实现 CORS 处理。