一般的基于浏览器跨域的主要解决方法有这么几种:1.JSONP       2.IFrame方式    3.通过flash实现  4.CORS跨域资源共享  ,这里我们主要关注的是在MVC里面的CORS跨域,其余的方式大家可以在网上找到相关的知识看一下。

  • CORS的原理:
     CORS定义一种跨域访问的机制,可以让AJAX实现跨域访问。CORS 允许一个域上的网络应用向另一个域提交跨域 AJAX 请求。实现此功能非常简单,只需由服务器发送一个响应标头即可。
      context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  • CORS浏览器支持情况如下图:
      
    
        也就是说除了IE8以下版本的浏览器不支持,其余的基于W3c标准的大部分都是支持的。
   

一般的针对ASP.NET MVC,cors跨域访问,只需要在web.config中添加如下的内容即可

<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>

<handlers>

<remove name="ExtensionlessUrlHandler-Integrated-4.0" />

<remove name="OPTIONSVerbHandler" />

<remove name="TRACEVerbHandler" />

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

</handlers>

</system.webServer>

但是这种全局设置存在局限性,因为你无法有选择性的设置可以跨域访问你本站的站点,所以就想到能不能通过特性标记控制器,或者标记控制器中的方法来设置跨域访问权限。

比如如下的方式

[ControllerAllowOrigin(AllowSites=new string[] { "aa.com" ,"bb.com"})]

public    class          TestController

{

}

这样你可以设置aa.com,bb.com跨域请求你站点TestController里面的任何数据接口方法

或者是如下方式:

public    class          TestController

{

[ActionAllowOrigin(AllowSites=new string[] { "aa.com" ,"bb.com"})]

public   JsonResult   Test()

{

}

}

设置aa.com,bb.com只能跨域请求你站点里面的TestController中的Test方法。

这样的话,我们控制起来就更加灵活方便,允许跨域访问本站的,在AllowSites里面添加地址就行了。

1.  基于控制器的跨域访问设置,这边我定义了一个ControllerAllowOriginAttribute,继承于AuthorizeAttribute

代码如下:

public class ControllerAllowOriginAttribute : AuthorizeAttribute
    {
        public string[] AllowSites { get; set; }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            AllowOriginAttribute.onExcute(filterContext, AllowSites);
        }

}

2.基于方法的跨域访问设置,我定义了一个ActionAllowOriginAttribute,继承于ActionFilterAttribute,

代码如下:

public class ActionAllowOriginAttribute : ActionFilterAttribute
    {
        public string[] AllowSites { get; set; }
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            AllowOriginAttribute.onExcute(filterContext, AllowSites);
            base.OnActionExecuting(filterContext);
        }
    }

核心代码其实很简单,就这么几行:

public class AllowOriginAttribute
    {
        public static void onExcute(ControllerContext context, string[] AllowSites)
        {
            var origin = context.HttpContext.Request.Headers["Origin"];
            Action action = () =>
            {
                context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);

};
            if (AllowSites != null && AllowSites.Any())
            {
                if (AllowSites.Contains(origin))
                {
                    action();
                }
            }
            
        }
    }

其中设置跨域访问权限的代码就是这一段HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);

完整的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace IocTEST.Common
{
public class AllowOriginAttribute
{
public static void onExcute(ControllerContext context, string[] AllowSites)
{
var origin = context.HttpContext.Request.Headers["Origin"];
Action action = () =>
{
context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin); };
if (AllowSites != null && AllowSites.Any())
{
if (AllowSites.Contains(origin))
{
action();
}
} }
} public class ActionAllowOriginAttribute : ActionFilterAttribute
{
public string[] AllowSites { get; set; }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
AllowOriginAttribute.onExcute(filterContext, AllowSites);
base.OnActionExecuting(filterContext);
}
}
public class ControllerAllowOriginAttribute : AuthorizeAttribute
{
public string[] AllowSites { get; set; }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
AllowOriginAttribute.onExcute(filterContext, AllowSites);
} } }

调用方式

[ControllerAllowOrigin(AllowSites = new string[] { "http://www.cnblogs.com" })]
    public class HomeController : Controller
    {

public JsonResult Test()
        {
            return Json(new { name = "aaa" }, JsonRequestBehavior.AllowGet);
        }

}

public class HomeController : Controller
    {

[ActionAllowOrigin(AllowSites = new string[] { "http://www.cnbeta.com" })]
        public JsonResult Test()
        {
            return Json(new { name = "aaa" }, JsonRequestBehavior.AllowGet);
        }

}

测试的时候,可以将需要跨域访问你本地localhost站点的网站打开,然后F12打开firebug,在console里面输入$.post('http://localhost:80/',{},function(){})或者

$.get('http://localhost:80/',{},function(){})  观察请求状态。

MVC跨域CORS扩展的更多相关文章

  1. 跨域CORS

    一.跨域CORS是什么 当一个资源从与该资源本身所在的服务器的域或端口不同的域或不同的端口请求一个资源时,浏览器会发起一个跨域 HTTP 请求.出于安全考虑,浏览器会限制从脚本内发起的跨域HTTP请求 ...

  2. netCore2.0 Api 跨域(Cors)

    1.在使用netCore2.0 使用WebApi的过程中涉及到了跨域处理. 在Microsoft.AspNetCore.All包中包含跨域Cors的处理,不必单独添加. 2.打开Startup.cs文 ...

  3. python 全栈开发,Day100(restful 接口,DRF组件,DRF跨域(cors组件))

    昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确.方便快速开发 - 针对pc,手机,ipad,微信,支付宝... 使用同一个接口 2. 简述http协议? - 基 ...

  4. IIS Manager 配置文件修该,允许跨域CORS访问

    IIS Manager 配置文件修该,允许跨域CORS访问 IIS Manager 的api访问会出现跨域问题,需要 IIS Manager的配置文件中修改. 配置文件的路径:C:\Program F ...

  5. zuul+security跨域Cors问题解决

    zuul+security跨域Cors问题解决 简介 场景 在服务后台都会出现跨域cors问题,不过一般spring解决起来比较方便,在框架+框架的基础上,问题就显得特别明显了,各种冲突,不了解源码的 ...

  6. 解决dotnet-Angular的跨域(cors)问题

    解决dotnet-Angular的跨域(cors)问题 前言 之前学了点 Angular ,打算用 dotnet core 做后端,之前没接触过这方面的东西,理所当然的遇到了跨域问题,之后也解决了,所 ...

  7. Spring MVC 后端接口支持跨域CORS调用

    Spring MVC 从4.2版本开始增加了对CORS的支持,可以全局配置,也可以对类或方法配置:可以通过Java代码,也可以通过xml配置方式. 对于低版本的Spring MVC 可以通过Filte ...

  8. Asp.Net 跨域,Asp.Net MVC 跨域,Session共享,CORS,Asp.Net CORS,Asp.Net MVC CORS,MVC CORS

    比如 http://www.test.com 和 http://m.test.com 一.简单粗暴的方法 Web.Config <system.web> <!--其他配置 省略……- ...

  9. 关于Spring MVC跨域

    1.Sping MVC 3.X跨域 关于跨域问题,主要用的比较多的是cros跨域. 详细介绍请看https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Ac ...

随机推荐

  1. Moon.Orm 常见查询实例

    一.Moon.Orm框架总述 (您还用hibernate?实体框架?) 1.框架名:Moon 意思是月亮,而非Mono.因为很喜欢明月,所以以此为名.它是一个.NET下的Orm框架. 2.发展历史:历 ...

  2. C#定时执行

    代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...

  3. Angular2中对ASP.NET MVC跨域访问

    应用场景 项目开发决定使用angular2进行前后端分离开发,由我负责后端服务的开发,起初选择的是web api进行开发.对跨域访问通过API中间件+过滤器对跨域访问进行支持.开发一段后,通知需要移植 ...

  4. 以下C#程序的输出结果是( )。

    以下程序的输出结果是( ). using System; namespace HoverTreeTikuConsole { class Program { static void Main(strin ...

  5. Entity Framework 教程——什么是Entity Framework

    什么是Entity Framework 编写和管理ADO.NET是一个繁琐而又无聊的工作.微软为你的应用提供了一个名为"Entity Framework"的ORM框架来自动化管理你 ...

  6. 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 我们在 读取配置文件(一) appsettings.json 中介绍了,如何读取appsettings.json. 但随之产生 ...

  7. C#开发微信门户及应用(19)-微信企业号的消息发送(文本、图片、文件、语音、视频、图文消息等)

    我们知道,企业号主要是面向企业需求而生的,因此内部消息的交流显得非常重要,而且发送.回复消息数量应该很可观,对于大企业尤其如此,因此可以结合企业号实现内部消息的交流.企业号具有关注安全.消息无限制等特 ...

  8. ORM是什么?如何理解ORM

    一.ORM简介         对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术.简单的说,ORM是通过使 ...

  9. 在阿里云中编译Linux4.5.0内核 - Ubuntu内核编译教程

    实验环境:Ubnuntu 64位(推荐使用14.04)+Xshell 阿里云现在提供的云服务器很好用的,用来编译内核性能也不错.本文介绍最基本的内核编译方法,为了方便,所有操作均在root用户下进行. ...

  10. 浅谈Linux内存管理机制

    经常遇到一些刚接触Linux的新手会问内存占用怎么那么多?在Linux中经常发现空闲内存很少,似乎所有的内存都被系统占用了,表面感觉是内存不够用了,其实不然.这是Linux内存管理的一个优秀特性,在这 ...