我正在尝试对我的 IIS 托管的 WebAPI 服务实施基本的 HTTP 身份验证。我试图使用 cookie 在服务器和客户端之间发送用户相关数据。当客户端是 Firefox 时,此代码似乎可以工作,但如果我使用 IE 或 Chrome,则 cookie 永远不会发送回服务器。
我有以下。
我将cookie添加到这样的响应消息中......在HttpModule.AuthenticateRequest-event handler中......
HttpApplication app = sender as HttpApplication;
HttpResponse response = app.Context.Response;
HttpRequest request = app.Context.Request;
HttpCookie c = new HttpCookie("MyCookie", "Hellou!");
c.Expires = DateTime.Now.AddDays(1);
c.Domain = request.Url.Host;
c.Path = "/";
response.Cookies.Add(c);
...或在控制器 POST 操作中:
CookieHeaderValue chv = new CookieHeaderValue("MyCookie", "Hellou");
chv.Expires = DateTime.Now.AddDays(1);
chv.Domain = Request.RequestUri.Host;
chv.Path = "/";
rmsg.Headers.AddCookies(new CookieHeaderValue[] { chv });
我在 HttpModule.AuthenticateRequest-event 处理程序中读取这样的 cookie
HttpApplication app = sender as HttpApplication;
HttpRequest request = app.Context.Request;
if (request.Cookies.Count > 0)
{
HttpCookie c = request.Cookies.Get("MyCookie");
if (c != null)
{
// ...
}
}
cookie 代码是否正确?有没有办法确保 cookie 在所有客户端都有效?