跨域CORS
/// <summary>
/// js跨域过滤器
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class CORSAttribute : Attribute, IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
/// <summary>
/// 扩展拦截
/// </summary>
/// <param name="serviceDescription"></param>
/// <param name="serviceHostBase"></param>
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatch in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher endpointDispatch in channelDispatch.Endpoints)
{
endpointDispatch.DispatchRuntime.MessageInspectors.Add(new CrossDomain());
}
}
} public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
2.
/// <summary>
/// js跨域过滤器
/// </summary>
public class CrossDomain : IDispatchMessageInspector
{
#region IDispatchMessageInspector
/// <summary>
/// token验证
/// </summary>
/// <param name="request"></param>
/// <param name="channel"></param>
/// <param name="instanceContext"></param>
/// <returns></returns>
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
if (CrossDomain.DealOptions(ref request))
{
return "";
}
return string.Empty;
} /// <summary>
/// 回复内容
/// </summary>
/// <param name="reply"></param>
/// <param name="correlationState"></param>
public void BeforeSendReply(ref Message reply, object correlationState)
{
if ((string)correlationState == "")
reply = MessageTempleHelper.GetDefault(JsonResultCode.SUCESS.ToString(), "OPTIONS");
else
CrossDomain.DealtMessage(ref reply);
}
#endregion /// <summary>
/// 对已处理的消息进行cross加工
/// </summary>
/// <param name="msg"></param>
public static void DealtMessage(ref Message msg)
{
try
{
var ct = ((HttpResponseMessageProperty)msg.Properties["httpResponse"]).Headers["Content-Type"]; if (MimeTypes.Contains(ct))
{
if (ct == MimeTypes[])
{
if (!msg.Properties.ContainsKey("WebBodyFormatMessageProperty"))
{
msg.Properties.Add("WebBodyFormatMessageProperty", new WebBodyFormatMessageProperty(WebContentFormat.Json));
}
else if (msg.Properties["WebBodyFormatMessageProperty"] == new WebBodyFormatMessageProperty(WebContentFormat.Xml)) //强制将xml返回值改为json
{
msg.Properties.Remove("WebBodyFormatMessageProperty");
msg.Properties.Add("WebBodyFormatMessageProperty", new WebBodyFormatMessageProperty(WebContentFormat.Json));
}
}
var property = new HttpResponseMessageProperty();
property.StatusCode = HttpStatusCode.OK;
property.Headers.Add("Content-Type", ct);
property.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
property.Headers.Add("Access-Control-Allow-Origin", "*");
property.Headers.Add("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,Accept,imUserID,accessToken,appkey,userID,token");
property.Headers.Add("Access-Control-Request-Methods", "GET, POST, PUT, DELETE, OPTIONS");
property.SuppressEntityBody = false;
property.SuppressPreamble = false;
if (msg.Properties.ContainsKey("httpResponse"))
msg.Properties.Remove("httpResponse");
msg.Properties.Add("httpResponse", property);
}
}
catch (Exception ex)
{
Log4NetUtil.WriteErrLog("CrossDomain.DealtMessage", ex);
}
} /// <summary>
/// 处理新的消息
/// </summary>
/// <param name="msg"></param>
public static void DealNewMessage(ref Message msg)
{
try
{
msg.Properties.Add("WebBodyFormatMessageProperty", new WebBodyFormatMessageProperty(WebContentFormat.Json));
var property = new HttpResponseMessageProperty();
property.StatusCode = HttpStatusCode.OK;
property.Headers.Add("Content-Type", MimeTypes[]);
property.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
property.Headers.Add("Access-Control-Allow-Origin", "*");
property.Headers.Add("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,Accept,imUserID,accessToken,appkey,userID,token");
property.Headers.Add("Access-Control-Request-Methods", "GET, POST, PUT, DELETE, OPTIONS");
property.SuppressEntityBody = false;
property.SuppressPreamble = false;
if (msg.Properties.ContainsKey("httpResponse"))
msg.Properties.Remove("httpResponse");
msg.Properties.Add("httpResponse", property);
}
catch { } } /// <summary>
/// 对当前请求是OPTIONS进行处理
/// </summary>
/// <param name="request"></param>
/// <returns>已处理为true,未处理为false</returns>
public static bool DealOptions(ref Message request)
{
try
{
if (((System.ServiceModel.Channels.HttpRequestMessageProperty)request.Properties["httpRequest"]).Method == "OPTIONS")
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,Accept,imUserID,accessToken,appkey,userID,token");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Request-Methods", "GET, POST, PUT, DELETE, OPTIONS");
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Accepted;
request.Close();
return true;
}
}
catch { }
return false;
} private static string[] _mimeTypes = null; /// <summary>
/// html格式
/// </summary>
public static string[] MimeTypes
{
get
{
if (_mimeTypes == null)
{
_mimeTypes = new string[] {
"application/json; charset=utf-8",
"image/png"
};
}
return _mimeTypes;
}
}
}
<script type="text/javascript">
$(function () {
$("button").click(function () { var postData = JSON.stringify({ name: "ASDF.txt", md5Code: "F006096956B5062F8EFB72AF4DF59BC2"}); console.log(postData); $.ajax({
url: "http://127.0.0.1:16060/FileService/GetInfo",
headers: {
imUserID: "e82287ac45c14040ba8ef34b9c2dac29",
accessToken: "U6wJgLoAdxVXUpx5R6AdZnFW/ytU+kgnVzaejZZoSdR31lNoRmDsQz42viOP7Jtm3iz8L2COA16r9rl5YUvZPhpHAAWxLNJBWWjHGKibHYejUuerO9qoxEkb6Yi+apPf60MzfmZ+SIgwhs6UBYOx2AbTkMdywYPCgKh8Q/mlVImUz0BU6WG4QCqgdqIefGi3"
},
contentType: "application/json; charset=utf-8",
type: "post",
dataType: "json",
data: postData,
success: function (data) {
$("#s").html(JSON.stringify(data));
console.log(data);
},
error: function (e) {
$("#e").html(e);
console.log(e);
}
});
}); });
</script>
测试结果:

跨域CORS的更多相关文章
- 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 做后端,之前没接触过这方面的东西,理所当然的遇到了跨域问题,之后也解决了,所 ...
- MVC跨域CORS扩展
一般的基于浏览器跨域的主要解决方法有这么几种:1.JSONP 2.IFrame方式 3.通过flash实现 4.CORS跨域资源共享 ,这里我们主要关注的是在MVC里面的CORS ...
- Js 跨域CORS报错 Response for preflight has invalid HTTP status code 405
问题 公司项目H5调用接口遇到Response for preflight has invalid HTTP status code 405这样的错误,是使用PUT方式提交请求接口.Content-T ...
- 浏览器和服务器实现跨域(CORS)判定的原理
前端对Cross-Origin Resource Sharing 问题(CORS,中文又称'跨域')应该很熟悉了.众所周知出于安全的考虑,浏览器有个同源策略,对于不同源的站点之间的相互请求会做限制(跨 ...
- Web高级 Ajax和跨域CORS
Asynchronous JavaScript and XML 1. XMLHttpRequest 前端开发都知道,不多说. var xhr = new XMLHttpRequest(); xhr.o ...
随机推荐
- stl_各容器的总结
一.stl容器总结: 1.以下的操作是在一千万的数据下操作.copy 都是在足够的空间下进行的copy, 测量方式: std::clock_t start = std::clock(); //待测代码 ...
- python结合shell脚本实现简单的日常集中巡检
一.环境配置 1.说明 下面的安装过程适合开发.调试Python脚本,如果是直接使用的话没有这么复杂.为了防止由于版本问题导致安装问题,请到http://pan.baidu.com/s/1nt1NKS ...
- JS中作用域
var scope = 'global'; var f = function() { console.log(scope); // 输出 undefined var scope = 'f'; } f( ...
- R语言结合概率统计的体系分析---数字特征
现在有一个人,如何对这个人怎么识别这个人?那么就对其存在的特征进行提取,比如,提取其身高,其相貌,其年龄,分析这些特征,从而确定了,这个人就是这个人,我们绝不会认错. 同理,对数据进行分析,也是提取出 ...
- [刷题]算法竞赛入门经典(第2版) 5-3/UVa10935 - Throwing cards away I
书上具体所有题目:http://pan.baidu.com/s/1hssH0KO 代码:(Accepted,0 ms) //UVa10935 - Throwing cards away I #incl ...
- Kafka学习-简介
Kafka是由LinkedIn开发的一个分布式的消息系统,使用Scala编写,它以可水平扩展和高吞吐率而被广泛使用.目前越来越多的开源分布式处理系统如Cloudera.Apache Storm.S ...
- 自己编写jQuery动态引入js文件插件 (jquery.import.dynamic.script)
这个插件主要是结合jquery或者xhr异步请求来使用的,它可以把已经引入过的js文件记录在浏览器内存中,当下次再引入相同的文件就忽略该文件的引入. 此插件不支持浏览器刷新保存数据,那需要利用cook ...
- window 远程在Linux(centOS7.0)上安装JDK以及配置环境变量
本人是在windows 7 上安装了虚拟机,虚拟机安装的是linux(centOS7.0)系统现在在Windows 上安装SecureCRT 远程虚拟机的linux系统,安装JDK以及配置环境变量. ...
- 基于本地文件系统的LocalDB
零.前言 之前写一些小工具的时候,需要用到数据存储方面的技术,但是用数据库又觉得太大了,本地文件存储txt文件存储又不是很规范,于是乎想到了去编写一个简单的基于本地文件系统的数据存储库,暂且叫它loc ...
- maven 热部署至tomcat
1.配置tomcat的界面访问账号和权限./tomcat/conf目录下tomcat-users.xml添加 这里是根据自己的需求添加的一个角色权限 <role rolename="a ...