asp.net web api2.0 ajax跨域解决方案
asp.net web api2.0 ajax跨域解决方案
Web Api的优缺点就不说了,直接说怎么跨域,我搜了一下,主要是有两种。
一,ASP.NET Web API支持JSONP,分两种
1,利用JsonMediaTypeFormatter,具体参考这里:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html
上代码:
新建JsonpMediaTypeFormatter类:

public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
{ private string callbackQueryParameter; public JsonpMediaTypeFormatter()
{
SupportedMediaTypes.Add(DefaultMediaType);
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript")); MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType));
} public string CallbackQueryParameter
{
get { return callbackQueryParameter ?? "callback"; }
set { callbackQueryParameter = value; }
} /// <summary>
/// 将对象序列化后的JSON字符串填充到JavaScript回调函数中
/// </summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <param name="stream"></param>
/// <param name="content"></param>
/// <param name="transportContext"></param>
/// <returns></returns>
public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
{
string callback; if (IsJsonpRequest(out callback))
{
return Task.Factory.StartNew(() =>
{
var writer = new StreamWriter(stream);
writer.Write(callback + "(");
writer.Flush(); base.WriteToStreamAsync(type, value, stream, content, transportContext).Wait(); writer.Write(")");
writer.Flush();
});
}
else
{
return base.WriteToStreamAsync(type, value, stream, content, transportContext);
}
} /// <summary>
/// 判断是否为跨域请求
/// </summary>
/// <param name="callback"></param>
/// <returns></returns>
private bool IsJsonpRequest(out string callback)
{
callback = null; if (HttpContext.Current.Request.HttpMethod != "GET")
return false; callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback);
}
}

- 在Global.asax中注册JsonpMediaTypeFormatter
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
2,利用ActionFilterAttribute ,具体参考这里:http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518
代码:
新建 JsonCallbackAttribute 类

public class JsonCallbackAttribute : ActionFilterAttribute
{
private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var callback = string.Empty;
if (IsJosnp(out callback))
{
var jsonBuilder = new StringBuilder(callback);
jsonBuilder.AppendFormat("({0})", actionExecutedContext.Response.Content.ReadAsStringAsync().Result);
actionExecutedContext.Response.Content = new StringContent("C(\"a\")");
}
base.OnActionExecuted(actionExecutedContext);
} private bool IsJosnp(out string callback)
{
callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter];
return !string.IsNullOrEmpty(callback);
} }

在Global.asax中注册JsonCallbackAttribute
GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
二,使用 Microsoft ASP.NET Web API 2 Cross-Origin Suppor
使用 NuGe 安装 Microsoft ASP.NET Web API 2 Cross-Origin Support,这里说的很详细
然后在Global.asax中开启针对CORS的支持,EnableCors加不加无影响的样子。
测试实例:

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>
<title>测试 WebApi 跨域</title>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="btnGet" value="Get 点击跨域查询数据" />
<div id="bindData">
</div>
<input type="button" id="btnPost" value="Post 点击跨域查询数据" />
</form>
<script>
$('#btnGet').bind('click', function (e) {
$.ajax({
type: "GET",
url: "http://localhost:20128/api/UserInfo",
success: function (data) {
var html = "";
$.each(data, function (index, val) {
html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>";
});
$("#bindData").append(html);
}
});
}); $('#btnPost').bind('click', function (e) {
var user = { Id: '1', Name: '233' };
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(user),
url: "http://localhost:20128/api/UserInfo",
success: function (data) {
//var html = "";
//$.each(data, function (index, val) {
// html += "<ul><li>GroupName: " + val.Id + " -- " + val.Name + "</li></ul>";
//});
//$("#bindData").append(html);
}
});
}); </script>
</body>
</html>

Ajax请求在Post数据的时候,一定要加上这样项:
contentType: 'application/json; charset=utf-8', data: JSON.stringify(user),
就这样,只是把网络上有解决方案的整理了一下,放在了一切。
asp.net web api2.0 ajax跨域解决方案的更多相关文章
- 使用Web代理实现Ajax跨域
目前的工作项目分为前端和后台,双方事先约定接口,之后独立开发.后台每天开发完后在测试服务器上部署,前端连接测试服务器进行数据交互.前端和后台分开的好处是代码不用混在一个工程里一起build,互不干涉. ...
- AJAX跨域解决方案
从AJAX诞生那天起,XMLHttprequest对象不能跨域请求的问题就一直存在,这似乎是一个很经典的问题了,是由于javascript的同源策略所导致. 解决的办法,大概有如下几种: 1. 使用中 ...
- Ajax跨域解决方案大全
题纲 关于跨域,有N种类型,本文只专注于ajax请求跨域(,ajax跨域只是属于浏览器"同源策略"中的一部分,其它的还有Cookie跨域iframe跨域,LocalStorage跨 ...
- 【PHP】Ajax跨域解决方案 、jsonp、cors
参考文章: 1.https://blog.csdn.net/u014727260/article/details/72793459 (后台java,实际上差不多) 2. 如何解决ajax跨域传输 数据 ...
- 前端Ajax跨域解决方案
业务场景: 前后端分离需要对接数据接口. 接口测试是在postman做的,今天才开始和前端对接,由于这是我第一次做后端接口开发(第一次嘛,问题比较多)所以在此记录分享我的踩坑之旅,以便能更好的理解,应 ...
- [妙味Ajax]第三课:AJAX跨域解决方案:JSONP
知识点总结: JSONP(JSON with Padding): 1.script标签 2.用script标签加载资源是没有跨域问题的 在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据), ...
- ajax跨域解决方案(服务端仅限java)
楼主前端知识菜鸟,高手勿喷,在此记录工作中遇到的问题及解决方案,大神请滤过 方法1.jsonp(js客户端ajax请求参数方式设置) 方法2.服务端接口设置: HttpServletResponse ...
- ajax跨域解决方案2
配置文件添加: <system.webServer> <httpProtocol> <customHeaders> &l ...
- 基于java过滤器实现的ajax跨域解决方案
http://software.dzhuvinov.com/cors-filter-configuration.html
随机推荐
- 《TCP/IP作品详细解释2:达到》注意事项--ARP:地址解析协议
Net/3于ARP和实施密切与路由表相关联的,下图显示了我们的叙述性说明ARP使用样品. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvVE9ERDkxMQ ...
- 2014年百度之星程序设计大赛 - 资格赛 1002 Disk Schedule(双调欧几里得旅行商问题)
Problem Description 有非常多从磁盘读取数据的需求,包含顺序读取.随机读取.为了提高效率,须要人为安排磁盘读取.然而,在现实中,这样的做法非常复杂.我们考虑一个相对简单的场景.磁盘有 ...
- Windows Phone 8 应用内截图
WriteableBitmap wb = new WriteableBitmap(this.LayoutRoot, new MatrixTransform()); //wb.Render(this.L ...
- HTM5 之 Canvas save 、restore 恢复画布状态的理解
save是用来保存canvas状态,这句话很关键,意思是指后续对canvas的操作:平移.放缩.旋转.错切.裁剪等可以恢复. 我之前一直没能理解,认为对画布的画线等操作也可以恢复,其实不是这样子的,只 ...
- 移动端 Retina屏 各大主流网站1px的解决方案
Retina屏的移动设备如何实现真正1px的线? 在retina屏下面,如果你写了这样的meta <meta name="viewport" content="in ...
- Intelli idea 常用快捷键汇总
To navigate to the implementation(s) of an abstract method, position the caret at its usage or its n ...
- (大数据工程师学习路径)第三步 Git Community Book----中级技能(下)
一.追踪分支 1.追踪分支 在Git中‘追踪分支’是用于联系本地分支和远程分支的. 如果你在’追踪分支'(Tracking Branches)上执行推送(push)或拉取(pull)时,它会自动推送( ...
- (大数据工程师学习路径)第一步 Linux 基础入门----文件系统操作与磁盘管理
介绍 本节的文件系统操作的内容十分简单,只会包含几个命令的几个参数的讲解,但掌握这些也将对你在学习后续其他内容的过程中有极大帮助. 因为本课程的定位为入门基础,尽快上手,故没有打算涉及太多理论内容,前 ...
- linux下一个eclipse组态jdk
今天ubuntu12.04安装eclipse,安装该想法eclipse后.还需要配置jdk.但没想到eclipse我有自己主动做好(但最主要的原因是我的linux在刚刚安装了一个jdk,假设有两个或更 ...
- HTML5 Introduction
1. HTML5 History HTML4.01 –1999.12 HTML5 – 2014.10– Done (8 years) In2006, WHATWG&W3C, decide to ...