WebAPI的跨域访问CORS三种方法
跨域访问:
JSONP的原理利用<script>没有跨域访问的限制,利用<script>的src跨域访问api,api会根据数据把json包装在一个js里面,这样跨域的客户端拿到json的包装(json padding)就会调用本地的函数解析数据。总结来说就是利用两点1、浏览器的跨域限制其实是接收了数据,但限制使用跨域数据。2是利用script标签可以跨域回调的功能
1、JSONP——js
api服务端
public HttpResponseMessage GetAllContacts(string callback)
{
Contact[] contacts = new Contact[]
{
new Contact{ Name="张三", PhoneNo="", EmailAddress="zhangsan@gmail.com"},
new Contact{ Name="李四", PhoneNo="", EmailAddress="lisi@gmail.com"},
new Contact{ Name="王五", PhoneNo="", EmailAddress="wangwu@gmail.com"},
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string content = string.Format("{0}({1})", callback, serializer.Serialize(contacts));
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(content, Encoding.UTF8, "text/javascript")
};
}
客户端
<head>
<title>联系人列表</title>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.10.2.js")"></script>
<script type="text/javascript">
function listContacts(contacts)
{
$.each(contacts, function (index, contact) {
var html = "<li><ul>";
html += "<li>Name: " + contact.Name + "</li>";
html += "<li>Phone No:" + contact.PhoneNo + "</li>";
html += "<li>Email Address: " + contact.EmailAddress + "</li>";
html += "</ul>";
$("#contacts").append($(html));
});
}
</script>
</head>
<body>
<ul id="contacts"></ul>
<script type="text/javascript" src="http://localhost:3721/api/contacts?callback=listContacts"></script>
</body>
</html>
2、JSONP——JsonMediaTypeFormatter
服务端定义类:
public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
{
public string Callback { get; private set; }
public JsonpMediaTypeFormatter(string callback = null)
{
this.Callback = callback;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (string.IsNullOrEmpty(this.Callback))
{
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
try
{
this.WriteToStream(type, value, writeStream, content);
return Task.FromResult<AsyncVoid>(new AsyncVoid());
}
catch (Exception exception)
{
TaskCompletionSource<AsyncVoid> source = new TaskCompletionSource<AsyncVoid>();
source.SetException(exception);
return source.Task;
}
} private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
{
JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
using (StreamWriter streamWriter = new StreamWriter(writeStream, this.SupportedEncodings.First()))
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter) { CloseOutput = false })
{
jsonTextWriter.WriteRaw(this.Callback + "(");
serializer.Serialize(jsonTextWriter, value);
jsonTextWriter.WriteRaw(")");
}
} public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
if (request.Method != HttpMethod.Get)
{
return this;
}
string callback;
if (request.GetQueryNameValuePairs().ToDictionary(pair => pair.Key, pair => pair.Value).TryGetValue("callback", out callback))
{
return new JsonpMediaTypeFormatter(callback);
}
return this;
} [StructLayout(LayoutKind.Sequential, Size = )]
private struct AsyncVoid{ }
}
注册到Global中
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
直接返回数据让系统自动协商优先使用
客户端:
$(function ()
{
$.ajax({
type: "GET",
url: "http://localhost:3721/api/contacts",
dataType: "jsonp",
success: listContacts
});
}); function listContacts(contacts) {
$.each(contacts, function (index, contact) {
var html = "<li><ul>";
html += "<li>Name: " + contact.Name + "</li>";
html += "<li>Phone No:" + contact.PhoneNo + "</li>";
html += "<li>Email Address: " + contact.EmailAddress
+ "</li>";
html += "</ul>";
$("#contacts").append($(html));
});
}
3、Microsoft AsRNET Web API2Cross-Origin support
原理:利用http的响应包标识Header;Access-Control-Allow-Origin等等标签标识允许跨域访问
Install-Package Microsoft.AspNet.WebApi.Cors
开启方法:
GlobalConfiguration.Configuration.EnableCors();
或在webapiconfig注册路由里开启
config.EnableCors();
api使用特性:
[EnableCors("http://localhost:9527","*","*")]
做全局配置Global/WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.clientA.com", "*", "*");
config.EnableCors(cors);
// ...
}
}
也可以只针对Controller或者Action做配置
[EnableCors(origins: "http://www.ClientA.com", headers: "*", methods: "*")]
public class ItemsController : ApiController
{
public HttpResponseMessage GetAll() { ... }
[EnableCors(origins: "http://www.ClientB.com", headers: "*", methods: "*")]
public HttpResponseMessage GetItem(int id) { ... }
public HttpResponseMessage Post() { ... } [DisableCors]
public HttpResponseMessage PutItem(int id) { ... }
}
WebAPI的跨域访问CORS三种方法的更多相关文章
- Ajax实现跨域访问的三种方法
转载自:http://www.jb51.net/article/68424.htm 一.什么是跨域 我们先回顾一下域名地址的组成: http:// www . google : 8080 / scri ...
- Ajax--跨域访问的三种方法
一.什么是跨域 我们先回顾一下域名地址的组成: / script/jquery.js http:// (协议号) www (子域名) google (主域名) (端口号) script/jquer ...
- Ajax实现跨域访问的两种方法
调程序时遇到"已拦截跨源请求:同源策略禁止读取位于--的远程资源",这是因为通过ajax调用其他域的接口会有跨域问题. 解决方法如下: 方法一:服务器端(PHP)设置header头 ...
- jQuery 跨域访问的三种方式 No 'Access-Control-Allow-Origin' header is present on the reque
问题: XMLHttpRequest cannot load http://v.xxx.com. No 'Access-Control-Allow-Origin' header is present ...
- System.Web.Http.Cors配置跨域访问的两种方式
System.Web.Http.Cors配置跨域访问的两种方式 使用System.Web.Http.Cors配置跨域访问,众多大神已经发布了很多文章,我就不在详细描述了,作为小白我只说一下自己的使用心 ...
- asp.net core webapi之跨域(Cors)访问
这里说的跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据.只要协议.域名.端口有任何一个不同,都被当作 ...
- 解决ajax跨域问题的一种方法
解决ajax跨域问题的一种方法 前后端分离经常用json来传输数据,比较常见的问题就有ajax跨域请求的错误问题,这里是我的一种解决方法: 在java中加入如下的注解类: import org.spr ...
- .Net WebApi 支持跨域访问使用 Microsoft.AspNet.WebApi.Cors
首先导入Cors库,通过程序包管理控制台导入 Install-Package Microsoft.AspNet.WebApi.Cors 引用库之后,我们需要进行简单的配置. 现在WebApiConfi ...
- 使用Cors后台设置WebAPI接口跨域访问
昨天根据项目组前端开发工程师反映,在浏览器端无法直接使用ajax访问后台接口获取数据,根据他的反映,我查阅了相关跨域的解决方案: 一:使用jsonP,但是jsonP只能使用GET请求,完全不符合我项目 ...
随机推荐
- ubuntu 搜狗输入法 在中断失效
实测是更换了皮肤后,出现在中断输入故障,乱码.在其他界面可能是正常的,更换语言没用. killall fcitx输入法突然好了(根据网友所说,更改一堆东西貌似并没有什么用) 此时关闭输入法皮肤一切正常 ...
- CH 4401/Luogu 4168 - 蒲公英 - [分块]
题目链接:传送门 题目链接:https://www.luogu.org/problemnew/show/P4168 题解: 经典的在线求区间众数的问题,由于区间众数不满足区间可加性,所以考虑分块,假设 ...
- [No000014C]让大脑高效运转的24个技巧
内容来译自David Rock “Your Brain at Work” and Nir Eyal, NirAndFar.com. Nir Eyal 是<上瘾>这本书的作者. 如何抓住转瞬 ...
- tensorflow的assgin方法
官网API是这么说的 This operation outputs a Tensor that holds the new value of 'ref' after the value has bee ...
- hive分析nginx日志之UDF清洗数据
hive分析nginx日志一:http://www.cnblogs.com/wcwen1990/p/7066230.html hive分析nginx日志二:http://www.cnblogs.com ...
- PPT文件分析摘记
将.pptx文件后缀改成.rar,然后解压 ppt文件夹下面是资源 [Content_Types].xml 展示是布局和内容说明的入口xml(显示的页面.页面对应的布局.内容.样式文件的路径),里面 ...
- 安装arcgis10.5不能启动服务的解决方案
最近由于公司需要,要装arcgis10.5,但是装这软件就费了好久的功夫.以前用的10.2,安装比较简单,但是10.5看起来就不一样了,下载完成后就会发现多了一个破解文件.按照教程一步一步安装的,但是 ...
- block diagonal matrix 直和 块对角矩阵 不完美 有缺陷 缩放 射影几何
小结: 1.block diagonal matrix 直和 块对角矩阵 A block diagonal matrix is a block matrix that is a square mat ...
- Instruments学习之Core Animation学习
当App发展到一定的规模,性能优化就成为必不可少的一点.但是很多人,又对性能优化很陌生,毕竟平常大多时间都在写业务逻辑,很少关注这个.最近在优化自己的项目,也收集了很多资料,这里先浅谈一下使用Inst ...
- 基于Gogs+Drone搭建的私有CI/CD平台
请移步 基于Gogs+Drone搭建的私有CI/CD平台