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.

<system.web> <httpCookies domain=".domain.com"/> </system.web>

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 .domain.com and not domain.com. 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:

var cookie = new HttpCookie(); cookie.Domain = ".domain.com";

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

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

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

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

The variable_domain is changed by the configuration file value.

This variable is also setted by the domain property.

public String Domain { get { return_domain;} set {_domain = value;_changed = true; } }