ASP.NET MVC实现跨域
准备工作
首先先创建Web应用程序,然后在控制器中实现返回Json数据的方法
public JsonResult getUser()
{
var res = new JsonResult();
res.Data = new object[]
{
new {id = 1,name = "wang",age = 12},
new {id = 2,name = "hong",age = 20}
};
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return res;
}
此时,直接访问该接口可以得到数据,但是若是要跨域请求,浏览器仍旧会报跨域请求失败的错误。
方法
对于Json数据来说,实现跨域请求的方法有两种:
一、配置Web.config
在项目下的Web.config配置文件中的****这个节点下加入这段配置
<system.webServer>
<httpProtocol>
<customHeaders>
<clear/>
<!-- value中可以填特定的域名,*表示对所有都实现 -->
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
二、添加filter
-
添加一个继承了ActionFilterAttribute的Filter类
using System.Web.Mvc; namespace TestThingJS.filter { public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*"); base.OnActionExecuting(filterContext); } } }
-
然后在需要实现的跨域的方法上添加注解
[AllowCrossSiteJson]//该注解用于开启filter public JsonResult getUser() { var res = new JsonResult(); res.Data = new object[] { new {id = 1,name = "wang",age = 12}, new {id = 2,name = "hong",age = 20} }; res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return res; }
注意:在本机测试时,可能会报其他错误**“ 已阻止载入混合活动内容 ”**
若使用的是Firefox浏览器
解决方法:
方法1:
- 打开新标签页,在地址栏输入 about:config,进入配置页面。
- 搜索 security.mixed_content.block_active_content,将true改为false。
方法2:
避免在HTTPS页面中包含HTTP的内容
例如, 从https提交内容到http,发现访问URL的时候确实是http的,将其改成https,就不再报错了。
若使用的是Google Chrome浏览器
解决方法:
方法:
在浏览器图标右键选择属性
在目标中加上 –allow-running-insecure-content即可
例如:
“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” --allow-running-insecure-content