asp.net web api2.0 ajax跨域解决方案

时间:2022-09-12 00:13:25

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类:

asp.net web api2.0 ajax跨域解决方案
    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);
}
}
asp.net web api2.0 ajax跨域解决方案
  • 在Global.asax中注册JsonpMediaTypeFormatter
  • GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());

  2,利用ActionFilterAttribute ,具体参考这里:http://*.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518

  代码:

新建 JsonCallbackAttribute 类

asp.net web api2.0 ajax跨域解决方案
    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);
} }
asp.net web api2.0 ajax跨域解决方案

在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加不加无影响的样子。

测试实例:

asp.net web api2.0 ajax跨域解决方案
<!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>
asp.net web api2.0 ajax跨域解决方案

Ajax请求在Post数据的时候,一定要加上这样项:

contentType: 'application/json; charset=utf-8',

data: JSON.stringify(user),

就这样,只是把网络上有解决方案的整理了一下,放在了一切。

 
分类: WebApi
标签: WebApi

asp.net web api2.0 ajax跨域解决方案的更多相关文章

  1. 使用Web代理实现Ajax跨域

    目前的工作项目分为前端和后台,双方事先约定接口,之后独立开发.后台每天开发完后在测试服务器上部署,前端连接测试服务器进行数据交互.前端和后台分开的好处是代码不用混在一个工程里一起build,互不干涉. ...

  2. AJAX跨域解决方案

    从AJAX诞生那天起,XMLHttprequest对象不能跨域请求的问题就一直存在,这似乎是一个很经典的问题了,是由于javascript的同源策略所导致. 解决的办法,大概有如下几种: 1. 使用中 ...

  3. Ajax跨域解决方案大全

    题纲 关于跨域,有N种类型,本文只专注于ajax请求跨域(,ajax跨域只是属于浏览器"同源策略"中的一部分,其它的还有Cookie跨域iframe跨域,LocalStorage跨 ...

  4. 【PHP】Ajax跨域解决方案 、jsonp、cors

    参考文章: 1.https://blog.csdn.net/u014727260/article/details/72793459 (后台java,实际上差不多) 2. 如何解决ajax跨域传输 数据 ...

  5. 前端Ajax跨域解决方案

    业务场景: 前后端分离需要对接数据接口. 接口测试是在postman做的,今天才开始和前端对接,由于这是我第一次做后端接口开发(第一次嘛,问题比较多)所以在此记录分享我的踩坑之旅,以便能更好的理解,应 ...

  6. &lbrack;妙味Ajax&rsqb;第三课:AJAX跨域解决方案:JSONP

    知识点总结: JSONP(JSON with Padding): 1.script标签 2.用script标签加载资源是没有跨域问题的 在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据), ...

  7. ajax跨域解决方案&lpar;服务端仅限java&rpar;

    楼主前端知识菜鸟,高手勿喷,在此记录工作中遇到的问题及解决方案,大神请滤过 方法1.jsonp(js客户端ajax请求参数方式设置) 方法2.服务端接口设置: HttpServletResponse ...

  8. ajax跨域解决方案2

    配置文件添加: <system.webServer>       <httpProtocol>        <customHeaders>          &l ...

  9. 基于java过滤器实现的ajax跨域解决方案

    http://software.dzhuvinov.com/cors-filter-configuration.html

随机推荐

  1. javascript中的prototype和constructor

    构造函数 我们知道,ECMAScript5中的Object.Array.Date.RegExp.Function等引用类型都是基于构造函数的,他们本身就是ECMAScript5原生的构造函数.比如,我 ...

  2. alphaRGB 转 RGB、16位

    struct xColor { BYTE b, g, r, a; }; struct RGBColor { BYTE b, g, r; }; //void operator <<(RGBC ...

  3. 连载《一个程序猿的生命周期》-6、自学C&plus;&plus;,二级考过后,为工作的机会打下了基础

    一个程序猿的生命周期 微信平台 口   号:职业交流,职业规划:面对现实,用心去交流.感悟. 公众号:iterlifetime 百木-ITer职业交流奋斗 群:141588103    微   博:h ...

  4. 【poj2455】 Secret Milking Machine

    http://poj.org/problem?id=2455 (题目链接) 题意 给出一张n个点,p条边的无向图,需要从1号节点走到n号节点一共T次,每条边只能经过1次,问T次经过的最大的边最小是多少 ...

  5. laravel打印sql语句

    打印sql语句,直接在你执行SQL语句后输出 方法一: $queries = DB::getQueryLog(); $a = end($queries); $tmp = str_replace('?' ...

  6. C&plus;&plus;成员变量内存对齐问题&comma;ndk下非对齐的内存访问导致BUS&lowbar;ADRALN

    同样的代码,在vs下运行正常,在android ndk下却崩溃: signal 7(SIGBUS),code 1 (BUS_ADRALN),fault addr 0xe6b82793 Func(sho ...

  7. redis sort

    redis sort命令用法 1.命令描述返回或保存给定列表.集合.有序集合key中经过排序的元素.排序默认以数字作为对象,值被解释为双精度浮点数,然后进行比较. 2.一般sort用法最简单的sort ...

  8. hive 配置mysql元数据库

    在 hive的配置文件hive-site.xml中 <?xml version="1.0"?> <!-- Licensed to the Apache Softw ...

  9. 在ASP&period;NET项目中使用CKEditor

    CKEditor是什么 CKEidtor是一个在线富文本编辑器,可以将让用户所见即所得的获得编辑在线文本,编辑器或自动将用户编辑的文字格式转换成html代码. 在ASP.NET工程中添加CKEdito ...

  10. 关于arguments&period;callee&period;caller&period;arguments&lbrack;0&rsqb;获得event的一些问题

    先从一个简单的例子说起,一个简单的button控件如下: < input  type ='button'  name ='mybtn'  id ='mybtn'  onclick ='myFun ...