我有一个Web API控制器,用于对用户进行身份验证并在响应上设置cookie:
// create the response
var response = this.Request.CreateResponse(HttpStatusCode.OK);
var cookie = new CookieHeaderValue(
FormsAuthentication.FormsCookieName,
user.GenerateEncryptedTicket(persistent)
);
var host = Request.RequestUri.Host;
// NOTE: this causes failure in Chrome if hosted locally (localhost)
// http://stackoverflow.com/a/5849409/99373
if (!host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
// are we in a sub-domain
if (host.Split('.').Length > 2)
{
// set the domain as '.domain.com'
// NOTE: this does not work in chrome
cookie.Domain = host.Substring(host.LastIndexOf('.', host.LastIndexOf('.') - 1));
}
else
{
// set the domain as 'domain.com'
// NOTE: this does not work in chrome either
cookie.Domain = host;
}
}
cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
cookie.Path = "/";
cookie.HttpOnly = true;
// mark the session as authenticated
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
不幸的是,这适用于IE和Firefox,但不适用于Chrome。如果我注释掉完全设置cookie.Domain
的部分,那么Chrome可以正常工作。
任何想法为什么?