DEV Community

Godwin Effiòng
Godwin Effiòng

Posted on

 

Creating HttpCookie Class in C#

Here, I want to Initialize Cookie in my Login Page. Firstly, what's a Cookie? This is a piece of information that's stored on the client's machine especially user preference information like Username, Password etc.

Now, Once logged in, I want the system to pull the user's records/information and store in the cookies. You can also set the number of times for your cookies login to be active, that's storing it and holding it for a particular duration. This here, makes it persistent or non-persistent.

Since, I want to initialize it on when "Logged-In", meaning I want Login records such as Username and Password etc.("UserInfo"). So, my block of code should be inside the Login Button click btnLogin_Click of my Login Page. So, I started off by creating the Cookie with the below block of code: E.g;

HttpCookie cookie = new HttpCookie("UserInfo");
Enter fullscreen mode Exit fullscreen mode

Then I Check if the cookie exists in the current request by reading the Cookie Info and displaying it and also printing the properties of each cookie object with the below code;

 if (cookie != null)
{
 //This here, prints the properties of each cookie object
 cookie.Values.Add("Username", cookie.StaffUsername);
 cookie.Values.Add("StaffNumber", cookie.StaffNumber);
 cookie.Values.Add("StaffName", (cookie.FirstName + " " + 
 cookie.LastName));
 cookie.Values.Add("Address", cookie.Address);
 cookie.Values.Add("StaffID", Convert.ToString(cookie.StaffID));

 // This here, Sets the value of cookie to current date time.
 cookie.Value = DateTime.Now.ToString();

 //This here, Sets expiry to cookie object -clears within an Hour.
 cookie.Expires = DateTime.Now.AddHours(1);

//This sets the HttpContext object for the current HTTP request.
 HttpContext.Current.Response.AppendCookie(cookie);
  }
Enter fullscreen mode Exit fullscreen mode

This is how I Initialized My cookie in my Login Page, I'll be writing more on Cookies as much as I'll be getting to use it.😊

Latest comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.