HttpCookie and web.config domain<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

HttpCookie and web.config domain

Posted on: July 12, 2012

You can set in your Asp.Net web.config file a domain for all your cookie. This is done by setting the httpcookies from the system.web.

2 <httpCookies domain=""/>

The main goal is to have all your cookies attached to the domain and not set to the subdomain. Also, notice that I have wrote and not This is important, otherwise, it won't work with subdomain.

So what does it do behind the scene? It simply set the domain property of the cookie to the domain name. In fact you could have code it manually:

1var cookie = new HttpCookie();
2 cookie.Domain = "";

Instead you set it once in the web.config. This is the constructor of HttpCookie. As you can see, it calls SetDefaultsFromConfig().

1public HttpCookie(String name, String value) {
2 _name = name;_stringValue = value;
3 SetDefaultsFromConfig();_changed = true;

This method goes into the web.config to get the domain.

1private void SetDefaultsFromConfig() {
2 HttpCookiesSection config = RuntimeConfig.GetConfig().HttpCookies;
3 _secure = config.RequireSSL;_httpOnly = config.HttpOnlyCookies;
5 if (config.Domain != null && config.Domain.Length > 0)
6 _domain = config.Domain;

The variable_domain is changed by the configuration file value.

This variable is also setted by the domain property.

1public String Domain {
2 get { return_domain;}
3 set {
4 _domain = value;
5 _changed = true;
6 }