【问题标题】:CORS Error when trying to return an Object from asp.net Web API 2 to Angular Front end尝试将对象从 asp.net Web API 2 返回到 Angular 前端时出现 CORS 错误
【发布时间】: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; 后,它工作正常

【问题讨论】:

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


【解决方案1】:

相信您需要将 OPTIONS 方法添加到您的 CorsEnableAttribute。

 var cors = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS");

您会注意到一个 Options 调用在 Get 请求执行一些飞行前嗅探之前发出。如果您不支持该方法,CORS 将无法工作。来自 Mozilla 的write up on CORS

规范要求浏览器“预检”请求, 使用 HTTP OPTIONS 从服务器请求支持的方法 请求方法,然后,在服务器“批准”后,发送 使用实际 HTTP 请求方法的实际请求。

【讨论】:

    猜你喜欢
    • 2020-03-24
    • 2018-06-23
    • 1970-01-01
    • 2019-08-18
    • 2017-06-03
    • 2019-11-09
    • 2017-12-01
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多