【发布时间】:2016-06-18 22:17:12
【问题描述】:
所以我有两个项目,一个是asp.net Web API2,另一个是Angular 1.5 Client。我开始很简单,只是返回一个对象列表,但是当我尝试这个时,我总是得到错误No 'Access-Control-Allow-Origin' header is present on the requested resource.,这让我很困惑,因为如果我返回一个字符串列表,我不会得到这个错误并且数据加载很好。
这是我的角度调用:
$http.get("http://localhost:53574/api/ReturnStringList")
.then(function(response) {
//success
console.log(response.data);
angular.copy(response.data, vm.links);
}, function (error) {
//failure
vm.errorMessage = "Failed to load data";
});
Web API 控制器方法
// GET api/DataController
[HttpGet]
public IEnumerable<string> Get()
{
var stringList= db.Links.Take(10).Select(x => x.LinkString).ToList();
return stringList;
}
// GET api/DataController/5
[HttpGet]
public IEnumerable<Link> Get(string id)
{
var links = db.Links.Take(10).ToList();
return links;
}
我的 Web API 的配置文件:WebApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("*", "*", "GET, POST");
config.EnableCors(cors);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
因此,如果我将获取 URL 更改为 api/ReturnStringList,它将很好地返回字符串列表,但如果我转到 api/ReturnStringList/5,它将返回以下错误,而无需我更改任何其他内容。
我检查了响应,我可以看到失败案例中的标头不存在,但后续案例中的标头显然存在,但我不明白为什么会发生这种情况。
编辑:我查看了@Jim G 建议的另一个主题,但没有解决。我正在使用建议的 NuGet 包,并且我已经按照注意事项调整了我的配置顺序而没有更改
**更新:** 我发现服务器出了点问题,在使用 fiddler 一段时间后,我发现对象没有被正确序列化。添加GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 后,它工作正常
【问题讨论】:
-
错误可能与配置有关。你的路由是怎么设置的?你能看到服务器上的错误吗?
-
@Irb 我把它设置得很简单,我已经将整个 Register 方法添加到问题中,除了我没有任何过滤器或其他 Api 配置,该方法是唯一在
Global.asax中调用的东西。至于错误,我没有看到任何错误。控制器方法从我设置的断点开始运行良好
标签: c# asp.net angularjs asp.net-web-api cors