跨域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 ...
随机推荐
- OSI七层模型学习笔记
1.简介 什么是OSI模型呢? OSI模型全名Open System InterConnect 即开放式系统互联,是国际标准化组织(ISO)提出的一个试图使各种计算机在世界范围内互连为网络的标准框架, ...
- C++模板学习:函数模板、结构体模板、类模板
C++模板:函数.结构体.类 模板实现 1.前言:(知道有模板这回事的童鞋请忽视) 普通函数.函数重载.模板函数 认识. //学过c的童鞋们一定都写过函数sum吧,当时是这样写的: int sum(i ...
- spring计划任务
Spring3中加强了注解的使用,其中计划任务也得到了增强,现在创建一个计划任务只需要两步就完成了: 创建一个Java类,添加一个无参无返回值的方法,在方法上用@Scheduled注解修饰一下: 在S ...
- javascript 函数和作用域(闭包、作用域)(七)
一.闭包 JavaScript中允许嵌套函数,允许函数用作数据(可以把函数赋值给变量,存储在对象属性中,存储在数组元素中),并且使用词法作用域,这些因素相互交互,创造了惊人的,强大的闭包效果.[upd ...
- JavaScript面向对象编程—this详解
this详解 作者的话 在JavaScriptOPPt面向对象编程中,this这位老大哥,相信大家不会陌生.大家在遇到this时,很多朋友难免会有个疑问:"这个this是什么,它到底指向 ...
- [刷题]算法竞赛入门经典 3-1/UVa1585 3-2/UVa1586 3-3/UVa1225
书上具体所有题目:http://pan.baidu.com/s/1hssH0KO(我也是在网上找到的pdf,但不记得是从哪里搜刮到的了,就重新上传了一遍) PS:第一次写博客分享我的代码,不知道我对c ...
- 反序列py脚本分享(原创)
代码如下: #!/usr/bin/env python # coding=utf-8 import socket import sys import requests import base64 im ...
- dubbo 入门
1 介绍 1.1 背景 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进. 1.2 说明 DUBB ...
- IE6.0升级的两种通用代码
随着W3C组织开始针对新的Web标准提案日期的到来,HTML5以及CSS3的新时代即将到来,同时微软的Win8以及IE10的出现也带给了这个世界奇妙的结构. 微软早在不再给WinXP做技术支持时,IE ...
- 【原创】JQWidgets-TreeGrid 2、初探源码
已知JQWidgets的TreeGrid组件依赖于jqxcore.js.jqxtreegrid.js,实际上它还依赖于jqxdatatable.js.我们先通过一个例子,来探索本次的话题. 需求: 图 ...