. NET get the cookie solution without JS write

Source: Internet
Author: User
Tags httpcontext set cookie

Use JavaScript tonight to set up an unsolicited cookie, then use ASP. NET to get the cookie value, found that ASP. js Set cookie value, really depressed, the following is the JS write cookie code:
Write cookies
Functionsetcookie (Name,value)
Document.cookie=name "=" Escape (value) ";"; /Set Cookie to close browsing is void
JS settings to route to a cookie
Setcookie ("Fromurl", document.referrer);
The following is the ASP. NET Read Cookie code:
Read cookies
<paramname= "STR" ></param>
Publicstringgetcookies (Stringkey)
if (system.web.httpcontext.current.request.cookies[key]!=null)
String_cstr=system.web.httpcontext.current.request.cookies[key]. Value.tostring ();
Encodingstre=encoding.getencoding ("UTF-8");
ReturnSystem.Web.HttpUtility.UrlDecode (_cstr,stre);
Returnstring. Empty;
Get cookies
Stringreferer=getcookies ("Fromurl");
Here, ASP. NET uses UTF-8 encoding to decode the value of the JS write cookie, otherwise the cookie will be slightly different.
Is the following code appears ASP. JS Write cookie, how to do it? Don't worry, here's the workaround:
Re-change the JS code, as follows:
Write cookies
Functionsetcookie (Name,value)
Document.cookie=name "=" Escape (value) ";p ath=/";//Cookies set to disable browsing
Add a path=/, it's all right. It's so simple.
  The path property of the cookie is set, and the Path= "/" attribute must be set on both the client and the server side to be able to interact with the cookie operation by JS and ASP! Another is the problem of coding, here JS in the code for encodeURI corresponding to the Server.URLEncode of ASP.

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.