0
我有一个奇怪的问题,我一直无法找到答案。.NET Web API CORS不适用于所有路由
我在我的Web API应用程序中多次使用CORS,以允许来自客户端应用程序的跨源请求而不会看到此问题。
在我WebApiConfig I类有:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
}
我有三个控制器方法与属性的路由:
[HttpPost]
[Route("pedigree")]
public IHttpActionResult GetPedigree([FromBody]Input input)
{
// some stuff
return Ok(result);
}
[HttpPost]
[Route("descendants")]
public IHttpActionResult GetDescendants([FromBody]Input input)
{
// some stuff
return Ok(result);
}
[HttpPost]
[Route("relatives")]
public IHttpActionResult GetRelatives([FromBody]Input input)
{
// some stuff
return Ok(person);
}
前两种方法做工精细,并返回数据。第三个没有,它与CORS失败:
XMLHttpRequest无法加载http://localhost:21870/api/familysearch/relatives。请求的资源上没有“Access-Control-Allow-Origin”标题。因此不允许访问原产地'http://localhost:8080'。响应有HTTP状态代码500。
我只是从角度做出一个Ajax请求的三种方法:
$http.post('http://localhost:21870/api/familysearch/relatives', postData)
.then(function (response) {
// do something
}).catch(function (e) {
// do something
});
人有什么想法?
感谢您的意见,我确实尝试过,但没有区别。无论如何,我的webapiconfig中的enablecors在所有控制器和方法中都应该是全局的。 – Starscream1984