Asp. NET the transfer of cookies data when Webapi and Ajax cross-domain data interaction

Source: Internet
Author: User
Tags httpcontext

This paper mainly introduces the knowledge of the data transfer of the cookies in the cross-domain data interaction between ASP and Ajax Webapi. Has a good reference value. Let's take a look at the little series.

Objective

Recently, the company's project restructuring, from the original three-tier architecture to upgrade to the micro-service architecture (accurate is the service, not exactly the degree of micro, granularity is not so fine), follow the Restfull specification, so that the front and rear end completely separated, to achieve a large front-end thinking. Because it is the first attempt, halfway also encountered a lot of problems. Let's talk about one of these issues today, when Webapi cross-domain data interactions with front-end Ajax, because they are under a different level two domain name (the same domain name), the cookie data cannot be retrieved.

It also solves the problem by transmitting cookies to their webapi through the head (header) at the very beginning.

Another solution is described below.

Resolution process:

Step one: Set the domain of the cookie to a domain name, for example: ". Wbl.com" (under a.wbl.com domain name)

This is the premise that when a cookie is set in one of the WEBAPI, it can be obtained by accessing the other WEBAPI directly with the browser. For example, cookies are provided under the a.wbl.com domain name, and the Webapi of the b.wbl.com domain name accessed directly from the browser can be obtained through cookies. However, with the Ajax access b.wbl.com under the c.web.com domain name, it is not possible to obtain cookies, which is due to the relatively low permissions of Ajax in the browser and the inability of Ajax to cross-domain issues.

Write the Cookie code:

123456789101112131415 /// <summary>  /// 给指定的 Cookies 赋值  /// </summary>  /// <param name="cookKey">Cookies 名称</param>  /// <param name="value">Cookies 值</param>  /// <param name="domain">设置与此 Cookies 关联的域(如:“.tpy100.com”)(可以使该域名下的二级域名访问)</param>  publicstaticvoidSetCookiesValue(stringcookKey, stringvalue, stringdomain)  {   HttpCookie cookie = newHttpCookie(cookKey);   cookie.Value = value;   cookie.HttpOnly = true;   if(!string.IsNullOrEmpty(domain) && domain.Length > 0)    cookie.Domain = domain;   HttpContext.Current.Response.Cookies.Add(cookie);  }

Step Two: Ajax uses JSONP data types to solve cross-domain issues (c.wbl.com domain name)

The front and back end needs to define a uniform callback (Callback) function name.

Front-end AJAX code:

123456789101112131415161718192021222324252627282930313233343536 // 设置Cookies  function set() {   varurl = "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  functionget() {   varurl = "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 three: Return JSONP data type in WEBAPI

JSONP format:

success_jsonpCallback({“Cookies”:”888888”})

Since this format differs from the JSON format, it is only possible to return the Ihttpactionresult or httprequestmessage type in the Webapi, and finally the output of the stream is implemented in this format.

Webapi Code:

1234567891011121314151617181920212223242526272829 [Route("api/GetValue")]  [HttpGet]  publicvoidGetValue()  {   stringccc = MyTools.Request.GetString("callbackparam");   vara = new{ name = "Cookies", value = MyTools.Cookies.GetCookiesValue("name") };   stringresult = 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]  publicvoidSetValue(intid)  {   //string domain = "";   stringdomain = ".wbl.com";   MyTools.Cookies.ClearCookies("name", domain);   MyTools.Cookies.SetCookiesValue("name", id.ToString(), domain);   stringccc = MyTools.Request.GetString("callbackparam");   stringresult = ccc + "({\"result\":\"设置成功\"})";   HttpContext.Current.Response.Write(result);   HttpContext.Current.Response.End();  }

Final effect:

After statement:

This is just one way to solve this problem. After Baidu also has a third-party plug-in (Cross-origin, help Page) to deal with, follow-up in the experiment.

Asp. NET the transfer of cookies data when Webapi and Ajax cross-domain data interaction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.