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 ...
随机推荐
- 我的EF功能
由来 话说这个功能想法由来与java的Hibernate功能,我需要一个类和数据库映射,很简单的写一个实体类简单配置一下就ok了, 很是方便, package com.game.po.log; imp ...
- 使用CoreProfiler/NanoProfiler实现跨平台&应用的整合性能调试
摘要 NanoProfiler是一个开源.NET性能调试类库,CoreProfiler是其.NET Core版本的实现.在之前的一些文章中,我曾介绍过NanoProfiler的主要使用方式,以及如何为 ...
- Basic Tutorials of Redis(4) -Set
This post will introduce you to some usages of Set in Redis.The Set is a unordered set,it means that ...
- 和Java相关的书籍,想成为架构师的请收藏一下啊
1.<<Effective Java 中文第二版>> 2.<<Java并发编程实践>> 3.<<Java核心技术(原书第8版)卷I_基础知识 ...
- 企业级应用架构模式N-Tier多层架构
先来看经典的3层架构,看下图: 涉及到平台可以是: Ruby on Rails, Java EE, ASP.NET, PHP, ColdFusion, Perl, Python 层 ...
- 通过Wireshark抓包进行Cookie劫持
首先在目标A机器上运行Wireshark并开启浏览器,开启前关闭其他占用网络的软件,这里我拿51CTO.com做测试. 正常登陆51CTO用户中心,此时使用 http.cookie and http. ...
- KOTLIN开发语言文档(官方文档) -- 入门
网页链接:https://kotlinlang.org/docs/reference/basic-syntax.html 1. 入门 1.1. 基本语法 1.1.1. 定义包 包说明应该在源 ...
- iOS - 捕获应用程序崩溃日志
作为一名iOS移动应用开发者,为了确保你的应用程序正确无误,在将应用程序提交到应用商店之前,你必定会进行大量的测试工作:而且在你测试的过程中应用程序运行的很好,但是在应用商店上线之后,还是有用户抱怨应 ...
- Struts2初始(一)
1.过滤器:org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter位置:在struts2的核心包struts2-co ...
- 【译】Spring 4 自动装配、自动检测、组件扫描示例
前言 译文链接:http://websystique.com/spring/spring-auto-detection-autowire-component-scanning-example-with ...