跨域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 ...
随机推荐
- Android开源项目库汇总
最近做了一个Android开源项目库汇总,里面集合了OpenDigg 上的优质的Android开源项目库,方便移动开发人员便捷的找到自己需要的项目工具等,感兴趣的可以到GitHub上给个star. 抽 ...
- 在Angular项目下使用Umeditor
Umeditor是百度旗下的开源富文本编辑器项目,目前用于百度贴吧,是ueditor的迷你版本. 公司的Angular后台管理项目需要上传一些新闻,用Umeditor十分适合.但是目前官方只提供Jsp ...
- OA办公系统,一个沉淀企业文化的容器
资源是会枯竭的,唯有文化才会生生不息.一切工业产品都是人类智慧创造的.随着公司规模的扩大,企业中两大根本"人和规则"面临诸多挑战,OA办公系统是一个全员使用的办公软件产品,员工可通 ...
- Mac电脑使用Android Studio进行真机调试
第一步: 为mac电脑配置 adb 命令的环境变量,分为2小步 1.找到 Android Studio 为你安装的 SDK : 打开电脑中 Android studio 的工具的软件,在启动 Andr ...
- python-day2 字典
===========字典功能=============> dict.clear() -->清空字典 dict.keys() -->获取所有key dict.values() --& ...
- 前端开发需要了解的JS插件
excanvas.js/Chart.js/cubism.js/d3.js/dc.js/dx.chartjs.js/echarts.js/flot.js 用途:构建数据统计图表,兼容多浏览器 jquer ...
- 基于Spring的轻量级工作流框架
项目地址 码云:https://git.oschina.net/null_584_3382/business-flow-parent github:https://github.com/Athlizo ...
- foreach底层机制
简单例子 直接了解foreach底层有些困难,我们需要从更简单的例子着手.下面上一个简单例子: public class Simple { public static void main(String ...
- js中的sort方法
js中原生的sort()采用快排和插入排序算法,根据比较器对数组排序. 默认是将数组元素转为字符串,然后根据Unicode字符集编号的大小排序. charCodeAt(index) 返回指定位置字符的 ...
- c语言项目开发流程二部曲
一.在第一部曲中我们介绍了电子词典项目开发的前5步,下面继续我们的步伐. 6.函数接口设计,这一步不是一蹴而就的,在项目进行中得不断修改,下面是我电子词典项目接口. /**************函数 ...