Home >Backend Development >C#.Net Tutorial >Regarding the transfer of Cookies data during cross-domain data interaction between WebAPI and Ajax in ASP.Net
This article mainly introduces the relevant knowledge of Cookies data transfer when ASP.Net WebAPI and Ajax interact with cross-domain data. Has very good reference value. Let’s take a look at it with the editor
Preface
Recently, the company’s project has undergone architectural adjustments, from the original three-tier architecture to a microservice architecture (accurate It is said to be service-oriented, but it has not yet reached the micro level, and the granularity is not that fine). It follows the RESTFull specification, completely separates the front and back ends, and realizes the idea of a big front end. Since this was my first attempt, I encountered many problems along the way. Today we will discuss one of the problems. When WebAPI and front-end Ajax interact with cross-domain data, since they are both under different second-level domain names (the first-level domain name is the same), Cookies data cannot be obtained.
Initially transmitting Cookies to its WebAPI through the header can also solve the problem.
Another solution is described below.
Solution process:
#Step 1: Set the Domain (domain) of Cookies to the first-level domain name, for example : ".wbl.com" (under the domain name a.wbl.com)
This is the premise. After setting Cookies in one of the WebAPIs, use the browser to access directlyOther WebAPIs can obtain Cookies. For example: Cookies set under the domain name a.wbl.com can be obtained by directly accessing the WebAPI of the domain name b.wbl.com with a browser. However, when using Ajax under the c.web.com domain name to access b.wbl.com, cookies cannot be obtained. This is due to the relatively low permissions of Ajax in the browser and the inability of Ajax to cross domain.
Write Cookies code:
/// <summary> /// 给指定的 Cookies 赋值 /// </summary> /// <param name="cookKey">Cookies 名称</param> /// <param name="value">Cookies 值</param> /// <param name="domain">设置与此 Cookies 关联的域(如:“.tpy100.com”)(可以使该域名下的二级域名访问)</param> 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); }
Step 2: JQuery uses the Jsonp data type in Ajax Solving cross-domain issues (under the c.wbl.com domain name)
The front and back ends need to define a unified callback (Callback)Functionname.
Front-end Ajax code:
// 设置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'); } }); }
Step 3: Return jsonp data type in WebAPI
Jsonp format:
success_jsonpCallback({"Cookies":"888888"})
Since this format is different from the json format, only return IHttpAction# in WebAPI ##Result or HttpRequestMessage type does not work. Finally, this format is realized through stream output.
WebAPI code:[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(); }Final effect: ##Afterword:
This Just one way to solve this problem. After Baidu, there is another way to handle it through third-party plug-ins (Cross-Origin, Help Page), and experiments will be carried out in the future. If any of you passing masters have a better method, please don’t be stingy and please enlighten me! Rookie is grateful!
The above is the detailed content of Regarding the transfer of Cookies data during cross-domain data interaction between WebAPI and Ajax in ASP.Net. For more information, please follow other related articles on the PHP Chinese website!