LearnFast.Ninja

How to use Cookies in ASP.NET using C# with example

In this tutorial you will see how to use Cookies in ASP.NET. In this example we using C# syntax. First we will check if the Cookie is not null, note in addition you can check if it is not empty string. If it is not null you can use the Cookie value, else you will set the Cookie. If you do not set time the expires will be when you close the browser session.

Working example code:

string Cookies_Value;

if (HttpContext.Current.Request.Cookies["ref"] != null)

{

    Cookies_Value = HttpContext.Current.Request.Cookies["ref"].Value;

}

else

{

    HttpContext.Current.Response.Cookies.Add(new HttpCookie("ref""utm_medium=cpc"));

    Cookies_Value = HttpContext.Current.Request.Cookies["ref"].Value;

}


Result:


Tags

asp.net

cookies cookie httpcookie ref utm_medium cpc expires