ASP.NET Session Cookies – specifying the base domain

By default, ASP.NET will set its cookies to use “mydomain.com” as their base. I’d prefer to have them use “www.mydomain.com” instead, so that I can have other “sub.mydomain.com” subdomains that are cookie-free.

I’ve done some digging into the Session and Cookie objects, and while I can find how to set the domain for a single cookie, I don’t see a way to set it for all Session cookies.

Anybody ideas?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Create a ISessionIDManager, since you only want to change the cookie domain we will let the default one do all the work.

This is configured in web.config on the sessionState element under <system.web>.

<sessionState sessionIDManagerType="MySessionIDManager" />

And the implementation.

public class MySessionIDManager: SessionIDManager, ISessionIDManager
{   
    void ISessionIDManager.SaveSessionID( HttpContext context, string id, out bool redirected, out bool cookieAdded )
    {
        base.SaveSessionID( context, id, out redirected, out cookieAdded );

        if (cookieAdded) {
            var name = "ASP.NET_SessionId";
            var cookie = context.Response.Cookies[ name ];
            cookie.Domain = "example.com";
        }
    }
}

Method 2

I realise this is an old question, but could you use the domain attribute of the httpCookies configuration section instead of doing this in code?

<httpCookies domain="String" 
             httpOnlyCookies="true|false" 
             requireSSL="true|false" />

Method 3

Session uses only one cookie, so why don’t you set domain only for ASP.NET_SessionId cookie ?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x