开发者

ASP.NET MVC cookies not saving?

Why doesn't this cookie save in the Session_Start me开发者_JAVA技巧thod 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 };
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜