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
随机推荐
- Linux删除以破折号开头的文件Windows在批处理文件来删除隐藏属性
昨天去打印店打印的材料.结果中毒.所有的文件被隐藏.生成一个一堆快捷键.回来后.我很容易地把它放入Linux机,我想删除这些文件怪. 下面是该过程,遇到的问题. 1.您无法删除'-'该文件的开头 最初 ...
- 职业选择測试(A/B卷)
不同性格的人适合从事不同的职业.职业选择对于每一个人都是很重要的事情.假设能选一个既可以发挥潜能又有兴趣的工作,会使整个团队的效率逐倍增长.想了解你更适合什么职业吗?一起来測试一下吧.本套測试分为A卷 ...
- Linux 的 Shell
一个:Shell 概念 shell 这个词是不奇怪,意思是 "壳" 这是间OS 用户和芯层之间的相互作用,在linux系统.用户可以通过命令终端.使用shell 命令向下传达他们的 ...
- 解决 Error:No suitable device found: no device found for connection "System eth0"
一.底 我们安装在虚拟机,.想模拟几台server.这时就想直接复制已经有的安装好的虚拟机.这样比較省事,不要在反复的安装虚拟机并配置JAVA环境,省掉做相同的事情,这时直接复制,这样之前配置的JAV ...
- ASP.NET MVC:01理解MVC模式
ASP.NET MVC是ASP.NET Web应用程序框架,以MVC模式为基础. MVC:Model View Controller 模型-视图-控制器Model(模型):负责对数据库的存取View( ...
- atitit.无线上网卡 无法搜索WiFi 解决无线路由器信号不能被连接
atitit.无线上网卡 无法搜索WiFi 解决无线路由器信号不能被连接 #---现象 pc机无线网卡无法搜索到无线路由器的信号.. 但是,笔记本电脑和手机能够... 只要pc机无线网卡可以搜索信号, ...
- 警告: git command could not be found. Please create an alias or add it to yo
5 Answers active answertab=oldest#tab-top" title="Answers in the order they were provided& ...
- SQL Server 2005------函数
原文:SQL Server 2005------函数 SQL Server 2005支持用户自定义函数和内置系统函数,根据返回值类型又分为标量函数和表值函数. 1.标量函数标量函数:返回单个数据值,返 ...
- emacs quick open and jump file (or buffer) which name is current word
Sometime, we need to open a file or buffer which name begin with current word in emacs. Here I give ...
- D - Cow Ski Area
Description Farmer John's cousin, Farmer Ron, who lives in the mountains of Colorado, has recently t ...