跨域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 ...
随机推荐
- Ubuntu16.04安装opencv for python/c++
Ubuntu16.04安装opencv for python/c++ 网上关于opencv的安装已经有了不少资料,但是没有一篇资料能让我一次性安装成功,因此花费了大量时间去解决各种意外,希望这篇能给一 ...
- 学好php可以做的事情真多!
学好php能做什么?其实学好php能做的事情很多! 一. 学好php可以就业 1:大中小公司通吃. 现在几乎所有有前途的公司都会在互联网上安家.只要在网上安家,就需要找这些方面的技术人员,而且很多公司 ...
- 【2017-05-03】winform打印控件、事件对象和事件数据、MDI窗体容器
一.打印控件 第一步先把打印对象搞出来. - printDocument 打印对象(将要打印的内容放到该对象里,从该对象里取内容打印) 设置他的PrintPage事件(对于要打印的每一页触发一次 ...
- IOS中常用的UIColor
UIColor + (UIColor *)blackColor; // 0.0 white 黑色 + (UIColor *)darkGrayColor; // 0.333 white 深灰色 + (U ...
- 【iOS UI】UINavigationController
1.UINavigationController介绍 1.1简介 UINavigationController可以翻译为导航控制器,在iOS里经常用到. 下面的图显示了导航控制器的流程.最左侧是根视图 ...
- 使用命令行的方式操作hdfs
必须要用打全路径,没有相对路径的概念,或者cd的概念 打印报告: 所有的命令显示出来: 以下的操作分别是创建创建文件夹,删除文件夹,显示文件夹,可见删除文件夹只能够使用-rmr . 从本地拷贝文件到h ...
- Linux文件属性及如何修改文件属性
ls -al:显示文件的文件名与相关属性并列出所有文件详细的权限与属性 dr-xr-x---. 7 root root 4096 Apr3 12:31 ...
- jQuery之筛选操作
jQuery之筛选操作 筛选操作分三大类:过滤,查找,串联 eq(),first(),last(),hasClass(),filter(),is() html代码 jQuery代码 效果如下: map ...
- error C2039: 'SetDefaultDllDirectories'错误解决办法
使用VS2013+WDK8.1+Win7开发UMDF驱动,当使用了CComPtr类,包含了atlcomcli.h头文件却报错,错误如下: Error 3 error C2039: 'SetDefaul ...
- .NET中webservice如何使用,调用
webservice 只是"面向服务"编程的一种方式,现在把所有的方式都合在一起,就叫做WCF,,,,,, 1.创建 webservice服务,在web项目中添加"web ...