我已经为您创建了一个简化的演示项目。
- 来源 :https : //github.com/bigfont/webapi-cors
- api链接 :https : //cors-webapi.azurewebsites.net/api/values
您可以从本地Fiddler 尝试上述 API链接 以查看标头。这是一个解释。
[Global.ascx](https://github.com/bigfont/webapi-
cors/blob/master/CORS/Global.asax.cs)
所有这一切都称为
WebApiConfig。只是代码组织而已。
public class WebApiApplication : System.Web.HttpApplication{ protected void Application_Start() { WebApiConfig.Register(GlobalConfiguration.Configuration); }}[WebApiConfig.cs](https://github.com/bigfont/webapi-
cors/blob/master/CORS/App_Start/WebApiConfig.cs)
您这里的关键方法是
EnableCrossSiteRequests方法。这就是您需要做的 所有
事情。该
EnableCorsAttribute是一个全球范围的CORS属性。
public static class WebApiConfig{ public static void Register(HttpConfiguration config) { EnableCrossSiteRequests(config); AddRoutes(config); } private static void AddRoutes(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "Default", routeTemplate: "api/{controller}/" ); } private static void EnableCrossSiteRequests(HttpConfiguration config) { var cors = new EnableCorsAttribute( origins: "*", headers: "*", methods: "*"); config.EnableCors(cors); }}[价值观控制器](https://github.com/bigfont/webapi-
cors/blob/master/CORS/Controllers/ValuesController.cs)
该
Get方法接收
EnableCors我们全局应用的属性。该
Another方法将覆盖global
EnableCors。
public class ValuesController : ApiController{ // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response.", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response. ", "It works only from two origins: ", "1. www.bigfont.ca ", "2. the same origin." }; }}[Web.config](https://github.com/bigfont/webapi-
cors/blob/master/CORS/Web.config)
您无需在web.config中添加任何特殊内容。实际上,这就是演示的web.config的样子-它是空的。
<?xml version="1.0" encoding="utf-8"?><configuration></configuration>
演示版
var url = "https://cors-webapi.azurewebsites.net/api/values"$.get(url, function(data) { console.log("We expect this to succeed."); console.log(data);});var url = "https://cors-webapi.azurewebsites.net/api/values/another"$.get(url, function(data) { console.log(data);}).fail(function(xhr, status, text) { console.log("We expect this to fail."); console.log(status);});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


