web api同源策略
1.重写JsonMediaTypeFormatter
public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
{
private string _callbackQueryParameter; public JsonpMediaTypeFormatter()
{
SupportedMediaTypes.Add(DefaultMediaType);
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/javascript")); // need a lambda here so that it'll always get the 'live' value of CallbackQueryParameter.
MediaTypeMappings.Add(new Mapping(() => CallbackQueryParameter, "application/javascript"));
} public string CallbackQueryParameter
{
get { return _callbackQueryParameter ?? "callback"; }
set { _callbackQueryParameter = value; }
} public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
TransportContext transportContext)
{
var callback = GetCallbackName(); if (!String.IsNullOrEmpty(callback))
{
// select the correct encoding to use.
Encoding encoding = SelectCharacterEncoding(content.Headers); // write the callback and opening paren.
return Task.Factory.StartNew(() =>
{
var bytes = encoding.GetBytes(callback + "(");
writeStream.Write(bytes, , bytes.Length);
})
// then we do the actual JSON serialization...
.ContinueWith(t => base.WriteToStreamAsync(type, value, writeStream, content, transportContext)) // finally, we close the parens.
.ContinueWith(t =>
{
var bytes = encoding.GetBytes(")");
writeStream.Write(bytes, , bytes.Length);
});
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
} private string GetCallbackName()
{
if (HttpContext.Current.Request.HttpMethod != "GET")
return null;
return HttpContext.Current.Request.QueryString[CallbackQueryParameter];
} #region Nested type: Mapping private class Mapping : MediaTypeMapping
{
private readonly Func<string> _param; public Mapping(Func<string> discriminator, string mediaType)
: base(mediaType)
{
_param = discriminator;
} public override double TryMatchMediaType(HttpRequestMessage request)
{
if (request.RequestUri.Query.Contains(_param() + "="))
return 1.0;
return 0.0;
}
} #endregion
}
在global中注册
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter ());
2.actionfilter
public class JsonCallbackAttribute
: ActionFilterAttribute
{
private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext context)
{
var callback = context.Request.GetQueryNameValuePairs().Where(item => item.Key == CallbackQueryParameter).Select(item => item.Value).SingleOrDefault(); if (!string.IsNullOrEmpty(callback))
{
var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result); context.Response.Content = new StringContent(jsonBuilder.ToString());
} base.OnActionExecuted(context);
}
}
web api同源策略的更多相关文章
- Cross-origin resource sharing JSON with Padding 同源策略 JSONP 为什么form表单提交没有跨域问题,但ajax提交有跨域问题? XMLHttpRequest and the Fetch API follow the same-origin policy 预检请求(preflight request)
https://zh.wikipedia.org/wiki/跨来源资源共享 跨来源资源共享(CORS)是一份浏览器技术的规范,提供了 Web 服务从不同域传来沙盒脚本的方法,以避开浏览器的同源策略[1 ...
- javascript 同源策略及web安全
同源策略为什么而生? JS可以读取/修改网页的值. 一个浏览器中,打开一个银行网站和一个恶意网站,如果恶意网站能够对银行网站进行修改,那么就会很危险. 你打开了恶意网站和另一个网站,如果没有同源限制, ...
- asp.net core 2.0 web api基于JWT自定义策略授权
JWT(json web token)是一种基于json的身份验证机制,流程如下: 通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端 ...
- Web - JSONP和同源策略漫谈
0x00 前言 关于JSONP网上有很多文章了,我也是在拜读了别人的文章的基础上来写写自己的看法,这样可以加深自己印象,巩固一下学习效果.我们需要做的就是站在巨人的肩膀上眺望远方. 0x01 起 在W ...
- web安全之同源策略
为什么使用同源策略?一个重要原因就是对cookie的保护,cookie 中存着sessionID .如果已经登录网站,同时又去了任意其他网站,该网站有恶意JS代码.如果没有同源策略,那么这个网站就能通 ...
- ArcGIS Server API for JavaScript调用错误:已阻止跨源请求:同源策略禁止读取位于......
已阻止跨源请求:同源策略禁止读取位于 http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapSe ...
- 通过扩展让ASP.NET Web API支持JSONP
同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...
- [CORS:跨域资源共享] 同源策略与JSONP
Web API普遍采用面向资源的REST架构,将浏览器最终执行上下文的JavaScript应用Web API消费者的重要组成部分."同源策略"限制了JavaScript的跨站点调用 ...
- 通过扩展让ASP.NET Web API支持W3C的CORS规范
让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...
随机推荐
- js模块化编程总结
大家都知道,js中的变量(variable)有其作用范围,比如:函数里用var定义的变量在函数外是看不到的,而定义在函数外面的变量(不能有没有var修饰)均是全局变量,在js程序的任何位置都可以访问. ...
- Oracle 中union的用法
UNION 指令的目的是将两个 SQL 语句的结果合并起来,可以查看你要的查询结果. 例如: SELECT Date FROM Store_Information UNION SELECT Date ...
- 最大的LeftMax与rightMax之差绝对值
这两天去 牛客网 混了下,遇到的几道题都很有意思,尤其是今晚这道,比赛时不会做,后来看了别人的代码才突然想通的,题目链接: 最大的LeftMax与rightMax之差绝对值,大意是: 想了一晚都没想出 ...
- flexbox弹性伸缩布局
<!doctype html><html lang="en"><head> <meta charset="UTF-8" ...
- nginx系统真正有效的图片防盗链完整设置详解
原文:http://www.wufangbo.com/nginx-fang-dao-lian/ 关于nginx防盗链的方法网上有很多教程,都可以用,但是我发现很多教程并不完整,所做的防盗链并不是真正的 ...
- D3.js 力导向图的制作
力导向图中每一个节点都受到力的作用而运动,这种是一种非常绚丽的图表. 力导向图(Force-Directed Graph),是绘图的一种算法.在二维或三维空间里配置节点,节点之间用线连接,称为连线. ...
- 转!!数据库 第一范式(1NF) 第二范式(2NF) 第三范式(3NF)的 联系和区别
范式:英文名称是 Normal Form,它是英国人 E.F.Codd(关系数据库的老祖宗)在上个世纪70年代提出关系数据库模型后总结出来的,范式是关系数据库理论的基础,也是我们在设计数据库结构过程中 ...
- 熟练使用git命令
git工作流程图: 下面是我整理的常用 Git 命令清单.几个专用名词的译名如下: Workspace:工作区 Index / Stage:暂存区 Repository:仓库区(或本地仓库) Remo ...
- jquery height
heigth -- 内容高度innerHeight -- 包含padding但不包含borderouterHeight -- 包含borderouterHeight(true) -- 包含margin ...
- C++ Primer 第三章 标准库类型vector+迭代器iterator 运算
1.vector: 标准库类型vector表示对象的集合,其中所有对象的类型都相同,集合中的每个对象都有一个与之对应的索引,索引用于访问对象.因为vector“容纳着”其他对象,所以它也常被称作容器( ...