使用Chrome开发者工具。我对WEB API资源的请求获得了取消状态。(网络标签)
服务器:WEB API 2.1 客户:Angular $ http请求
初始消息称CORS违规为原因。我在服务器上启用了CORS。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Going camel case in Web API http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// cors support
var cors = new EnableCorsAttribute( "http://localhost:9168/", "*", "*");
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
}
}
在实施CORS之后,我仍然会在API调用中取消响应消息,但是,当钻入消息时,数据将从服务器返回。
我检查了Fiddler并且请求标头正确传递了原始等,但是我仍然收到此错误:
XMLHttpRequest cannot load http://localhost:4416/api/LookupTrades. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9168' is therefore not allowed access.
有关Chrome中取消状态的帖子似乎很多,所有帖子都有不同的原因。不知道下一步该怎么做。有什么想法吗?
答案 0 :(得分:-1)
安装Nuget包`“Microsoft.AspNet.WebApi.Cors”(version =“5.1.0”)
在WebApiConfig.cs文件中添加以下行
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
您还可以在ajax调用之前在js文件中设置此属性
$.support.cors = true;