ASP.NET Cookie Domains HTTP HTTPS
Posted by in CSharp March 27, 2012 Leave a comment

In order to preserve cookies across primary domain and its sub domains with or without www and between http and https, you can check out a piece of asp.net written in C# code below:

1. Writing Cookie

Example below will write a cookie “your_cookie_name ” with value “your cookie value” and set the cookie’s domain property to yourdomain.com:

string cookie_str = "your cookie value";
Response.Cookies["your_cookie_name"].Value = cookie_str;
Response.Cookies["your_cookie_name"].Domain = "yourdomain.com";

2. Reading Cookie

Response.Write("Your cookie has been written with value: " + HttpContext.Current.Request.Cookies["your_cookie_name"].Value.ToString());

The cookie will then be available to the primary domain (yourdomain.com) as well as to all its sub domains such as: subdomain1.yourdomain.com, subdomain2.yourdomain.com, etc.

It’s also available when you try to access through HTTP or HTTPS with or without www such as: https://yourdomain.com or https://www.yourdomain.com

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com