简体   繁体   中英

How to read a cookie in C#?

I'm not sure how to read a web cookie in C#. I tried this code, but I get multiple errors.

        private string GetCookieValue(string cookieName, string itemName)
        {
            var CookieName = "MY_COOKIE";
            var CookieValue = string.empty;
                                //     ^ error

            HttpCookie myCookie = Request.Cookies[CookieName];
            // ^ error              // ^ error           
            if (myCookie == null) 

            {
                return "No Cookie Found.";
            }


            CookieValue = myCookie.Value.ToString();

            return CookieValue;
        }

Any help would be appreciated, thanks.

(sorry about that) Errors:

line 4, 'string' does not contain a definition for 'empty' line 5, the type or namespace name 'HttpCookie' could not be found. line 5, The name Request does not exist in the current context.

You need to use string.Empty and not empty. For reading of cookie, see below example:

public static string GetFromCookie(string cookieName, string keyName)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
    if (cookie != null)
    {
        //Logic placeholder
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM