简体   繁体   中英

ASP.NET MVC cookies not saving?

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);

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.

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 };
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM