栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Asp.Net WebApi2启用CORS无法与AspNet.WebApi.Cors 5.2.3一起使用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Asp.Net WebApi2启用CORS无法与AspNet.WebApi.Cors 5.2.3一起使用

我已经为您创建了一个简化的演示项目。

  • 来源 :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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432984.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号