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


一般的针对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扩展的更多相关文章
- 跨域CORS
		
一.跨域CORS是什么 当一个资源从与该资源本身所在的服务器的域或端口不同的域或不同的端口请求一个资源时,浏览器会发起一个跨域 HTTP 请求.出于安全考虑,浏览器会限制从脚本内发起的跨域HTTP请求 ...
 - netCore2.0 Api 跨域(Cors)
		
1.在使用netCore2.0 使用WebApi的过程中涉及到了跨域处理. 在Microsoft.AspNetCore.All包中包含跨域Cors的处理,不必单独添加. 2.打开Startup.cs文 ...
 - python 全栈开发,Day100(restful 接口,DRF组件,DRF跨域(cors组件))
		
昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确.方便快速开发 - 针对pc,手机,ipad,微信,支付宝... 使用同一个接口 2. 简述http协议? - 基 ...
 - IIS Manager 配置文件修该,允许跨域CORS访问
		
IIS Manager 配置文件修该,允许跨域CORS访问 IIS Manager 的api访问会出现跨域问题,需要 IIS Manager的配置文件中修改. 配置文件的路径:C:\Program F ...
 - zuul+security跨域Cors问题解决
		
zuul+security跨域Cors问题解决 简介 场景 在服务后台都会出现跨域cors问题,不过一般spring解决起来比较方便,在框架+框架的基础上,问题就显得特别明显了,各种冲突,不了解源码的 ...
 - 解决dotnet-Angular的跨域(cors)问题
		
解决dotnet-Angular的跨域(cors)问题 前言 之前学了点 Angular ,打算用 dotnet core 做后端,之前没接触过这方面的东西,理所当然的遇到了跨域问题,之后也解决了,所 ...
 - Spring MVC  后端接口支持跨域CORS调用
		
Spring MVC 从4.2版本开始增加了对CORS的支持,可以全局配置,也可以对类或方法配置:可以通过Java代码,也可以通过xml配置方式. 对于低版本的Spring MVC 可以通过Filte ...
 - 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> <!--其他配置 省略……- ...
 - 关于Spring MVC跨域
		
1.Sping MVC 3.X跨域 关于跨域问题,主要用的比较多的是cros跨域. 详细介绍请看https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Ac ...
 
随机推荐
- JS性能优化
			
1.不要在同一行声明多个变量. 2.请使用 ===/!==来比较true/false或者数值 3.使用对象字面量替代new Array这种形式 4.不要使用全局函数. 5.Switch语句必须带有de ...
 - 小试ASP.NET MVC——一个邀请页面的实现
			
上篇博客我们大体介绍了ASP.NET MVC以及如何去新建项目,这篇博客我们讲点干货.小试ASP.NET MVC,我们来写一个简单的邀请WEB. 先来建立一个Models,叫GuestResponse ...
 - 在公有云AZURE上部署私有云AZUREPACK以及WEBSITE CLOUD(四)
			
(四)搭建Website Cloud环境 1安装CONTROLLER主机 在开始安装Web site Cloud之前,读者应该对该服务的拓扑结构有个大概了解. 如图: Controller是非常重要的 ...
 - Gradle project sync failed
			
在Android Studio中运行APP时出现了以下错误: gradle project sync failed. please fix your project and try again 解决的 ...
 - yii框架安装心得
			
最近在学习yii框架, 现在将遇到的一些问题和解决方法写出来与大家分享. yii框架的安装: 下载yii框架之后, 打开文件运行init.bat文件, 如果闪退就打开php的扩展(php_openss ...
 - 解决mysql too many connections的问题
			
由于公司服务器上的创建的项目太多,随之创建的数据库不断地增加,在用navicat链接某一个项目的数据库时会出现too many connections ,从而导致项目连接数据库异常,致使启动失败. 为 ...
 - django 第二天 制作小demo
			
创建虚拟目录 mkdir ~/virtualenvs mkdir ~/virtualenvs/myprojectenv virtualenv ~/virtualenvs/myprojectenv 激活 ...
 - 用gcc进行程序的编译
			
在Linux系统上,一个档案能不能被执行看的是有没有可执行的那个权限(x),不过,Linux系统上真正认识的可执行文件其实是二进制文件(binary program),例如/usr/bin/passw ...
 - jquery 金额转换成大写
			
<script language="javascript" type="text/javascript"> function Ara ...
 - ITIS-资料集合贴
			
ITIS-资料集合贴 说明:这个贴用于收集笔者能力范围内收集收藏并认为有用的资料,方便各方参考,免去到处找寻之苦,提升信息的交叉引用价值.另外,笔者就自己感悟做了部分评注,且可能尝试不断的优化分类和排 ...