为了账号安全,请及时绑定邮箱和手机立即绑定

在Web API 2中启用CORS

在Web API 2中启用CORS

C#
忽然笑 2019-12-26 14:05:03
我有客户端和服务器在不同的端口上运行。服务器正在运行Web API 2(v5.0.0-rc1)。我尝试安装Microsoft ASP.NET Web API跨域支持包,并在中启用了它WebApiConfig.cs。它提供了我的EnableCors()功能,因此该软件包已正确安装。在这里,您可以看到我的Register()功能WebApiConfig.cs:public static void Register(HttpConfiguration config){    config.MapHttpAttributeRoutes();    var cors = new EnableCorsAttribute("*", "*", "*");    config.EnableCors(cors);}GET请求工作正常。但是在发送时POST,我得到以下信息:OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.根据Fiddler的说法,它仅发送OPTIONS请求。POST以后不发行。所以我猜config.EnableCors(cors);在WebApiConfig.cs没有做任何事情,这导致服务器拒绝客户端/浏览器发送一个POST请求。您有解决该问题的想法吗?编辑05.09.13 这已在5.0.0-rtm-130905中修复
查看完整描述

3 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

CORS在Microsoft.AspNet.WebApi.Cors5.2.2版本中绝对可以正常工作。以下步骤将CORS配置为我的魅力:


Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" //从程序包管理器控制台运行

在Global.asax中,添加以下行:在任何MVC路由注册之前


GlobalConfiguration.Configure(WebApiConfig.Register);

在WebApiConfigRegister方法中,具有以下代码:


public static void Register(HttpConfiguration config)

{

    config.EnableCors();

    config.MapHttpAttributeRoutes();

}

在web.config中,以下处理程序必须是管道中的第一个处理程序:


<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

在从派生的控制器中ApiController,添加EnableCorsAttribute:


[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs

[RoutePrefix("")]

public class MyController : ApiController

那应该可以很好地设置您!


查看完整回答
反对 回复 2019-12-26
  • 3 回答
  • 0 关注
  • 429 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信