Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Cookies data transfer in Cross-domain data interaction between WebAPI and Ajax in ASP.Net

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

这篇文章主要介绍ASP.Net中WebAPI与Ajax进行跨域数据交互时Cookies数据传递的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

本文主要介绍了ASP.Net WebAPI与Ajax进行跨域数据交互时Cookies数据传递的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧

前言

最近公司项目进行架构调整,由原来的三层架构改进升级到微服务架构(准确的说是服务化,还没完全做到微的程度,颗粒度没那么细),遵循RESTFull规范,使前后端完全分离,实现大前端思想。由于是初次尝试,中途也遇到了不少问题。今天就来讨论一下其中之一的问题,WebAPI与前端Ajax 进行跨域数据交互时,由于都在不同的二级域名下(一级域名相同),导致Cookies数据无法获取。

最开始通过头部(Header)将Cookies传输到其WebAPI,也能解决问题。

下面讲述另外一种解决方案。

解决过程:

步骤一:将Cookies的Domain(域)设置成一级域名,例如:".wbl.com"(a.wbl.com域名下)

这是前提,此时在其中一个WebAPI中设置了Cookies后,用浏览器直接访问其它的WebAPI是可以获取到Cookies的。例如:a.wbl.com域名下设置的Cookies,用浏览器直接访问b.wbl.com域名的WebAPI是可以获取到Cookies的。但是用c.web.com域名下的Ajax访问b.wbl.com时,就无法获取到Cookies了,这是由于浏览器中Ajax的权限相对较低,Ajax无法跨域问题导致。

写入Cookies代码:

/// /// 给指定的 Cookies 赋值 /// /// Cookies 名称 /// Cookies 值 /// 设置与此 Cookies 关联的域(如:".tpy100.com")(可以使该域名下的二级域名访问) public static void SetCookiesValue(string cookKey, string value, string domain) { HttpCookie cookie = new HttpCookie(cookKey); cookie.Value = value; cookie.HttpOnly = true; if (!string.IsNullOrEmpty(domain) && domain.Length > 0) cookie.Domain = domain; HttpContext.Current.Response.Cookies.Add(cookie); }

步骤二:JQuery中Ajax使用Jsonp数据类型解决跨域问题(c.wbl.com域名下)

前后端需要定义统一的回调(Callback)函数名。

前端Ajax代码:

// 设置Cookies function set() { var url = "http://a.wbl.com/api/setvalue/888888"; $.ajax({ type: "get", url: url, dataType: "jsonp", jsonp: "callbackparam", //服务端用于接收callback调用的function名的参数 jsonpCallback: "success_jsonpCallback", //callback的function名称 success: function (json) { console.log(json); alert(json); }, error: function () { alert('fail'); } }); } // 获取Cookies function get() { var url = "http://b.wbl.com/api/getvalue"; $.ajax({ type: "get", url: url, dataType: "jsonp", jsonp: "callbackparam", //服务端用于接收callback调用的function名的参数 jsonpCallback: "success_jsonpCallback", //callback的function名称 success: function (json) { console.log(json); alert(json); }, error: function () { alert('fail'); } }); }

步骤三:WebAPI中返回jsonp数据类型

Jsonp格式:

success_jsonpCallback({"Cookies":"888888"})

由于这种格式与json格式有所不同,只用WebAPI里的返回IHttpActionResult或HttpRequestMessage类型不行,最后通过流的方式输出才实现了这个格式。

WebAPI代码:

[Route("api/GetValue")] [HttpGet] public void GetValue() { string ccc = MyTools.Request.GetString("callbackparam"); var a = new { name = "Cookies", value = MyTools.Cookies.GetCookiesValue("name") }; string result = ccc + "({\"Cookies\":\"" + MyTools.Cookies.GetCookiesValue("name") + "\"})"; //var response = Request.CreateResponse(HttpStatusCode.OK); //response.Content = new StringContent(result, Encoding.UTF8); HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); // return response; } [Route("api/SetValue/{id}")] [HttpGet] public void SetValue(int id) { //string domain = ""; string domain = ".wbl.com"; MyTools.Cookies.ClearCookies("name", domain); MyTools.Cookies.SetCookiesValue("name", id.ToString(), domain); string ccc = MyTools.Request.GetString("callbackparam"); string result = ccc + "({\"result\":\"设置成功\"})"; HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); }

最终效果:

The above is "ASP.Net WebAPI and Ajax cross-domain data interaction when the cookie data transfer sample analysis" All the content of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report