Web API 跨域访问(CORS)

1.在web.config里把“    <remove name="OPTIONSVerbHandler" />  ”删掉。

2. 到nuget上装一个包:    http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors/  

3. 注册使用CORS

方法一:

在WebApiConfig.Register方法中加入代码:

config.EnableCors();

在Controller或Action上加上Attribute:

[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]

方法二:

在WebApiConfig.Register方法中加入代码:

var cors = new EnableCorsAttribute("http://www.contoso.com,http://www.example.com", "*", "*");
config.EnableCors(cors);

在Controller或Action上加上Attribute:

[EnableCors]

在不需要跨域访问的Action上,可以加上Attribute:

[DisableCors]

这个域名可以配置单个,也可以配置多个,具体可参考官网教程:

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

最后,在服务端完提供支持以后,不要高兴的太早,如果你用jQuery.ajax()的方式去请求,还是会报错的:

$.ajax({
    url: 'yourCORSurl',
    data: '',
    dataType: 'json',
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    ...
})

经过无数次爆破,终于发现,只要把dataTypecontentType两个参数去掉,就肯定不会报错了!!!虽然不知道为什么,但代码能用了。

原文地址:https://www.cnblogs.com/sky-net/p/5956867.html