0

当我将 $http.post 从客户端发送到不同项目的 web api 时,firebug 和 chrome 都显示 OPTIONS 方法,然后显示 POST 方法。

问题
两个请求实际上都执行了我的 API 操作。如果我限制为 POST,则 OPTIONS 会失败,并且帖子永远不会发生。我在 angular 和 webapi 中都打开了 CORS。

我的 app.js 有以下几行:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With']; 

我的 API 调用:

    $scope.add = function () {
        var role = { Name: 'admin' };
        $http.post('http://localhost:7514/Roles/add', role).
            success(function () {
                alert('RolesController.add');
            }).
            error(function (message) {
                alert('FAILED EXECUTE RolesController.add');
            });
    };

webapi web.config

<system.webServer>
...
<!-- added for cors handling, remove when using a dedicated cors handler or the system.web.cors dll-->
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>
</system.webServer>
4

1 回答 1

0

如果您使用每晚 CORS 包,OPTIONS 请求会被不执行操作但仍发送适当响应标头的消息处理程序拦截。有关更多信息以及如何使用每晚包,您应该查看这篇关于获取 CORS 每晚包的博客文章。

http://blogs.msdn.com/b/yaohuang1/archive/2013/04/05/try-out-asp.net-web-api-cors-support-using-the-nightly-builds.aspx

确保从下拉列表中选择“Prerelease”。

于 2013-06-24T15:04:12.700 回答