Using cookie in asp.net mvc c#

倾然丶 夕夏残阳落幕 提交于 2019-11-28 15:59:53
Yannis

I m not sure I understand if this is a question about how to properly send cookies to the client or some bug with your querystring params. So I ll post the proper way of sending cookies and feel free to correct me if I misunderstood.

In any case though, I believe this:

HttpCookie cookie = new HttpCookie("search");

will reset the search cookie

To get a cookie:

HttpCookie cookie = HttpContext.Request.Cookies.Get("some_cookie_name");

To check for a cookie's existence:

HttpContext.Request.Cookies["some_cookie_name"] != null

To save a cookie:

HttpCookie cookie = new HttpCookie("some_cookie_name");
HttpContext.Response.Cookies.Remove("some_cookie_name");
HttpContext.Response.SetCookie(cookie );
Shiva Saurabh

i have organised the cookie fetching and inserting in an organized manner such that it can be used throughout the application. for that purpose i put two methods SetCookie and GetCookie.

You can simply put this class in your code and work out.

Here i put my class with the static methods

public class CookieStore
{
    public static void SetCookie(string key, string value, TimeSpan expires)
    {
        HttpCookie encodedCookie = HttpSecureCookie.Encode(new HttpCookie(key, value));

        if (HttpContext.Current.Request.Cookies[key] != null)
        {
            var cookieOld = HttpContext.Current.Request.Cookies[key];
            cookieOld.Expires = DateTime.Now.Add(expires);
            cookieOld.Value = encodedCookie.Value;
            HttpContext.Current.Response.Cookies.Add(cookieOld);
        }
        else
        {
            encodedCookie.Expires = DateTime.Now.Add(expires);
            HttpContext.Current.Response.Cookies.Add(encodedCookie);
        }
     }
    public static string GetCookie(string key)
    {
        string value = string.Empty;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            // For security purpose, we need to encrypt the value.
            HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
            value = decodedCookie.Value;
        }
        return value;
    }

}

using these you can easily store values in cookie and fetch value whenever required

using these methods is as simple as

For Setting Cookie:

CookieStore.SetCookie("currency", "GBP", TimeSpan.FromDays(1)); // here 1 is no of days for cookie to live

For Getting Cookie:

string currency= CookieStore.GetCookie("currency");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!