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:
/// <summary> ///Assign a value to a specified cookie/// </summary> /// <param name= "Cookkey" >Cookie Name</param> /// <param name= "value" >Cookie Value</param> /// <param name= "domain" >set up the domain associated with this cookie (for example, ". Tpy100.com") (You can access the two-level domain name under the domain name)</param> Public Static voidSetcookiesvalue (stringCookkey,stringValuestringdomain) {HttpCookie Cookie=NewHttpCookie (Cookkey); Cookies. Value=value; Cookies. 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:
//Set CookiesfunctionSet() { varURL ="http://a.wbl.com/api/setvalue/888888"; $.ajax ({type:"Get", Url:url, DataType:"Jsonp", Jsonp:"Callbackparam",//the parameters of the service side used to receive the function name of the callback callJsonpcallback:"Success_jsonpcallback",//function Name of the callbacksuccess:function (JSON) {console.log (JSON); alert (JSON); }, Error:function () {alert ('fail'); } }); } //Access to CookiesfunctionGet() { varURL ="Http://b.wbl.com/api/getvalue"; $.ajax ({type:"Get", Url:url, DataType:"Jsonp", Jsonp:"Callbackparam",//the parameters of the service side used to receive the function name of the callback callJsonpcallback:"Success_jsonpcallback",//function Name of the callbacksuccess: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:
[Route ("Api/getvalue")] [HttpGet] Public voidGetValue () {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] Public voidSetValue (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\": \ "set success \"})"; 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. You pass the great God if there is a better way, hope not stingy, please enlighten! Rookie Thank you!
The transfer of cookies data when ASP. NET WEBAPI interacts with Ajax for cross-domain data