简体   繁体   English

启用跨域ASP.net Web API

[英]Enabling Cross Domain ASP.net Web API

I have Microsoft Visual Studio Express 2013 for Web, Version 12.0.30501.00 Update 2. I have a solution with 2 project in it, one is a web api, and the second is an MVC project intended for for the views. 我有Microsoft Visual Studio Express 2013 for Web,版本12.0.30501.00更新2.我有一个包含2个项目的解决方案,一个是web api,第二个是用于视图的MVC项目。 I have create a simple web api returning httpresponsemessage and I can go in fiddler and I will see the json response. 我创建了一个简单的web api返回httpresponsemessage,我可以进入fiddler,我会看到json响应。 However in my second project when attempting to call through ajax I received a cross domain error. 但是在我尝试通过ajax调用的第二个项目中,我收到了跨域错误。

The solution I try to follow is this http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api . 我试图遵循的解决方案是http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api However when installing Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService in the console manager I received an error so I used this line instead. 但是,当在控制台管理器中安装Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService ,我收到了一个错误,所以我使用了这一行。 Install-Package Microsoft.AspNet.WebApi.Cors then I try to the next step which is config.EnableCors(); Install-Package Microsoft.AspNet.WebApi.Cors然后我尝试下一步是config.EnableCors(); its state that 它的状态

'System.Web.Http.HttpConfiguration' does not contain a definition for 'EnableCors' and no extension method 'EnableCors' accepting a first argument of type 'System.Web.Http.HttpConfiguration' could be found (are you missing a using directive or an assembly reference?)

I am not sure what to afterward, I also try to add using System.Web.Http.Cors; 我不知道后来会发生什么,我也尝试using System.Web.Http.Cors;添加using System.Web.Http.Cors; but state that the namespace does not exists. 但声明命名空间不存在。 This visual studio was downloaded about 3 weeks ago, I feel this feature should not be hard to install as it fully supported, is there something that i am missing? 这个视觉工作室是在大约3周前下载的,我觉得这个功能不应该很难安装,因为它完全支持,有什么我缺少的东西?

You should install a Nuget package Microsoft.AspNet.WebApi.Cors 您应该安装Nuget包Microsoft.AspNet.WebApi.Cors

From the menu in visual studio, go to Management Packages, and then type in the name of the package 从visual studio的菜单中,转到Management Packages,然后键入包的名称

Note: 注意:
To install from Package Manager Console , use Install-Package Microsoft.AspNet.WebApi.Cors 要从Package Manager控制台进行 Install-Package Microsoft.AspNet.WebApi.Cors ,请使用Install-Package Microsoft.AspNet.WebApi.Cors

install a Nuget package `"Microsoft.AspNet.WebApi.Cors" (version="5.1.0") 安装Nuget包`“Microsoft.AspNet.WebApi.Cors”(version =“5.1.0”)

Add following line in your WebApiConfig.cs file 在WebApiConfig.cs文件中添加以下行

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM