ASP.NET MVC实现跨域

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:

  1. 打开新标签页,在地址栏输入 about:config,进入配置页面。
  2. 搜索 security.mixed_content.block_active_content,将true改为false。

方法2:

避免在HTTPS页面中包含HTTP的内容

例如, 从https提交内容到http,发现访问URL的时候确实是http的,将其改成https,就不再报错了。

若使用的是Google Chrome浏览器

解决方法:

方法:

  1. 在浏览器图标右键选择属性

  2. 在目标中加上 –allow-running-insecure-content即可

    例如:

    “C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” --allow-running-insecure-content

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值