DEV Community

Godwin Effiòng
Godwin Effiòng

Posted on

1

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.😊

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay