方案一
在WebConfig 的根目录下,添加
<!--跨域-->
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>
原文链接:https://blog.csdn.net/qq_29072459/article/details/100882484
方案二
在NuGet中引入一程序包,这个包的名字叫做 Microsoft.AspNet.WebApi.Cors
安装完程序包之后,需要(在App_Start里面的WebApiConfig.cs)添加如下配置
config.EnableCors(); 一定要添加这个,才能使用EnableCorsAttribute,否则,在Contoler或者Action上面添加这个特性无效
如果需要在某个Controler或者action执行跨域,其它的不执行跨域,只需要添加特性 [EnableCors(origins: “", headers: "”, methods: “*”)] 即可
origins:表示的是可以访问当前接口的域名或者IP
例如 origins: “http://localhost:8081/”
methods:表示可以请求当前接口的方法
例如 methods: “GET,POST,PUT,DELETE”)
headers:自定义的头部
如果某个Action不要执行跨域,则添加DisableCors特
如果要配置全局的跨域,则在App_Start里面的WebApiConfig.cs添加Config.EnableCors(new EnableCorsAttribute("","","*"));