7

Why doesn't this cookie save in the Session_Start method of my global.asax?

//new anon user:

var authCookie = new HttpCookie("user-id", string.Format("{0}-{1}", regiserAccountResponse.UserName, regiserAccountResponse.Key))
{
    Expires = DateTime.MaxValue,
    Domain = "domain.com",
    Secure = true,
    HttpOnly = true
};

//create the new users cookie - there's no need to call RegisterNewUserSession as this is done in the same call
HttpContext.Current.Response.SetCookie(authCookie);
4
  • 1
    How are you detecting whether it's actually saved? Have you used Wireshark to see whether it's coming down? Have you fixed the domain and secure bits to reflect reality? Commented Nov 26, 2010 at 13:51
  • should i leave domain blank until i'm ready to deploy? or should it be localhost until i deploy? Commented Nov 26, 2010 at 13:54
  • 1
    Try removing it entirely. It's not like you're really serving "domain.com" is it? I can't say I know much about cookies, but those settings definitely look wrong... Commented Nov 26, 2010 at 13:55
  • thanks jon - remd the secure and domain props and it seems to work now - if you add that to an answer i'll mark it correct :) Commented Nov 26, 2010 at 13:58

2 Answers 2

7

You only need to specify the Domain if you want to limit the cookie to a specific section of your website. The cookie will only be included in the request if it is in the correct scope.

By setting the Domain to "domain.com", you are saying that the cookie will only be available to "domain.com", so you won't detect it from localhost (or from any other domain other than domain.com").

You will also notice that if you try and send a browser a cookie from a domain other than your own, the browser will bin it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks steve! Both right - looks like it's working now so all good in da hood... :)
Svet svet baby. Hope the new job is sound.
0

iOS is now pretty keen to bin domainless cookies asap, so while the accepted answer says "You only need to specify the Domain if you want to limit the cookie to a specific section of your website" - I don't think this is true. You need to set a domain.

The following snippet will work from local through to production:

    private static HttpCookie CreateCookie(string name, string value)
    {
        return new HttpCookie(name, value) { Path = "/", Expires = DateTime.UtcNow.AddYears(1), Domain = Request.Url.Host };
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.