A Cookie is a small amount of text that attached to the requet and response in between browser and the server. This small amount of text can be read by the application whenever user browse the it. Please note that cookie is not a good medium to store the confidential data as it is stored into the user browser.
Let's learn how to limit the scope of the cookie creation so that those cookie will be available only to a particular domain or sub domain.
<asp:Button ID="btnCookieSet" runat="server" Text="Set Cookie" OnClick="SetCookie" />
<asp:Button ID="btnCookieGet" runat="server" Text="Get Cookie" OnClick="GetCookie" />
In the above snippet, we have two buttons. Clicking on first button executes SetCookie method and clicking on the second button executes GetCookie method.
// how to test
// Access this page and set the cookie, then get the cookie value.
// Now try to access this page with other domain (in local machine, simply access this page with different localhost:port).
protected void SetCookie(object sender, EventArgs e)
// set the cookie
Response.Cookies["MyCookie"].Value = "My cookie for a domain";
Response.Cookies["MyCookie"].Domain = "localhost"; //"training.dotnetfunda.com";
protected void GetCookie(object sender, EventArgs e)
if (Request.Cookies["MyCookie"] != null)
string cookieValue = Request.Cookies["MyCookie"].Value;
This method creates a cookie for “localhost” (as I have developed this page on local machine so I have tested with localhost) domain by setting the domain property of the Cookie.
Note that in case we have created the cookie for main domain, that cookie works for all subdomains as well but if the cookie has been created for the sub-domain, it doesn’t work for the parent domain or other sub domain.
If cookie domain has been set to “dotnetfunda.com”, that cookie will be available for “training.dotnetfunda.com”, “blog.dotnetfunda.com” and any other sub domains. But if the domain has been set to “training.dotnetfunda.com” at the time of cookie creation, that cookie will not be available on “dotnetfunda.com” or “blog.dotnetfunda.com”.
This method checks for the cookie, if it is not null then prints its value on the page.
In the above picture you can see that MyCookie has been created for domain "localhost".
In case you have missed earlier article series on Cookies in ASP.NET, click here.