asp.net web api2.0 ajax跨域解决方案
2024-08-28 17:38:03
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),
就这样,只是把网络上有解决方案的整理了一下,放在了一切。
最新文章
- javascript高级教程:如何优化javascript代码性能
- JVM 运行时数据区域
- C++中的vector使用范例
- 论文笔记之:Active Object Localization with Deep Reinforcement Learning
- AD转换精度的计算
- .net 禁止远程查看应用程序错误的详细信息,服务器上出现应用程序错误
- android 录制视频方式
- VR全景是继互联网后的第二王朝吗?
- web工作过程
- UOJ275 [清华集训2016] 组合数问题 【Lucas定理】【数位DP】
- Newtonsoft.Json2.0下面序列化和反序列化
- 快速构建springmvc+spring+swagger2环境
- Codeforces gym101612 L.Little Difference(枚举+二分)
- Java 多线程(三)之线程状态及其验证
- HDU 4640 状态压缩DP 未写完
- cv::Mat到YUV420的转换《转》
- OpenCV3.4.1+vs2017安装及配置
- 第六周小组作业 软件测试与评估:百词斩VS扇贝单词
- [GO]tcp网络通信和实现
- win10出现";win10系统即将过期,请激活";的处理办法
热门文章
- HDU2149-Public Sale
- RH133读书笔记(11)-Lab 11 System Rescue and Troubleshooting
- leetcode-2 Add Two Numbers 计算两个对应的列表和问题
- MVC的验证 jquery.validate.unobtrusive
- 自己的自定义单元格(IOS)
- cocos2dx --- button点击放大中心
- REST WebService
- php用魔术方法__call实现类函数重载
- 在ABP项目的应用Castle Windsor
- ABP