Monday, June 3, 2013

// // Leave a Comment

Get or Set Http Cookies in server side of C# on Asp.Net Website

Set and Get Cookies


get cookie in code behind of asp.net website


 Get Cookie 

Sample Code
      HttpCookie myCookie = new HttpCookie("sampleCookie");
      SampleCookie= Request.Cookies["sampleCookie"];

      // Read the cookie information and display it.
      if (SampleCookie!= null){
          string value= SampleCookie.Value;
          string name= SampleCookie.Name;

Explanation

1.Create an object for the HttpCookie Class

      HttpCookie myCookie = new HttpCookie("sampleCookie");

2. Get the Cookie from Request.Cookies Collection

      SampleCookie= Request.Cookies["view"];

3.Check whether the cookie object is null
      if (SampleCookie!= null)
4. Get the Cookie Value and Cookie Name
          string value= SampleCookie.Value;
          string name= SampleCookie.Name;


Set Cookie


Sample Code

HttpCookie SampleCookie= new HttpCookie("SampleCookie");
SampleCookie.Value="SampleName";
SampleCookie.Name="SampleValue";
myCookie.Domain="sampleDomain.com"
SampleCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(SampleCookie);


0 comments:

Post a Comment