.NET Web API CORS不适用于所有路由

时间:2016-06-14 16:12:14

标签: .net angularjs asp.net-web-api cors

我有一个奇怪的问题,我无法找到答案。

我在Web API应用程序中多次使用CORS来允许来自客户端应用程序的跨源请求,而不会出现此问题。

在我的WebApiConfig课程中,我有:

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
    });

有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要在控制器类上添加EnableCors属性,以启用特定WebAPI上的CORS Controller

[EnableCors("*", "*", "*")]