在 Web API 2 中启用 CORS [英] Enable CORS in Web API 2

查看:30
本文介绍了在 Web API 2 中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有客户端和服务器在不同的端口上运行.服务器正在运行 Web API 2 (v5.0.0-rc1).

I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).

我尝试安装 Microsoft ASP.NET Web API Cross-Origin Support package 和在 WebApiConfig.cs 中启用它.它给了我 EnableCors() 函数,所以包安装正确.

I tried installing the Microsoft ASP.NET Web API Cross-Origin Support package and enabled it in WebApiConfig.cs. It gives me the EnableCors() function, so the package was installed correctly.

在这里你可以看到我在WebApiConfig.cs中的Register()函数:

Here you can see my Register() function in WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
}

GET 请求工作正常.但是在发送 POST 时,我得到以下信息:

GET requests work fine. But when sending POST, I get the following:

OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.

根据 Fiddler 的说法,它只发送 OPTIONS 请求.之后它不会发出 POST.

According to Fiddler it only sends the OPTIONS request. It doesn't issue the POST afterwards.

所以我猜WebApiConfig.cs中的config.EnableCors(cors);没有做任何事情,这导致服务器拒绝客户端/浏览器发送 POST 请求.

So I'm guessing the config.EnableCors(cors); in the WebApiConfig.cs isn't doing anything, which leads to the server denying the client/browser to send a POST request.

你知道如何解决这个问题吗?

Do you have any idea how to solve this problem?

编辑 05.09.13这已在 5.0.0-rtm-130905 中修复

EDIT 05.09.13 This has been fixed in 5.0.0-rtm-130905

推荐答案

我肯定遇到了这个问题 带有属性路由.问题已修复 5.0.0-rtm-130905.但是,您仍然可以尝试 nightly builds 肯定会有修复.

I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.

要将 nightlies 添加到 NuGet 包源,请转到 Tools ->库包管理器 ->包管理器设置并在 Package Sources 下添加以下 URL:http://myget.org/F/aspnetwebstacknightly

To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly

这篇关于在 Web API 2 中启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆