3

我有一个利用cookie 来支持准向导的应用程序(即,它是一组相互导航到的页面,它们必须以特定的顺序出现,以便注册)。

Logon.aspx页面加载时 - 默认页面 - 浏览器 cookie 看起来是正确的。

在这里,我们只有一个 cookie。

有一个 cookie,它具有正确的价值。这可确保作为注册协议的下一页知道它是从该Logon.aspx页面加载的。但是,当我到达该页面时,浏览器的 cookie 看起来有很大不同:

现在我们有两个相同的cookie。

现在我们有两个相同的cookie。

这似乎不会导致任何真正的问题 - 但我不能确定它不会。所以,让我向您展示我用来设置 cookie 的代码(因为它可能有问题):

if (!this.IsPostBack)
{
    Utility.HandleReferrer(Request, Response, "Logon.aspx");
    Response.Cookies["lastpage"].Value = "Enroll.aspx";
}

HandleReferrer方法如下所示:

static public void HandleReferrer(HttpRequest request, HttpResponse response, string expectedReferrer)
{
    var cookie = request.Cookies["lastpage"];
    if (cookie != null && cookie.Value.ToLower().Contains(expectedReferrer.ToLower()))
    {
        return;
    }

    response.Redirect("Logon.aspx");
}

那么,为什么它会复制这个 cookie?它似乎永远不会创造超过两个。

4

2 回答 2

2

我建议您执行以下操作之一。

首先,获取最新一瞥,然后再试一次。

如果它仍然显示 2 个具有该名称的 cookie,则获取firebug和/或fiddler并以这种方式查看。如果我不得不猜测,我会说一瞥有问题,或者你解释结果的方式有问题。也许一瞥正在显示在处理请求之前和之后存在哪些 cookie?

第三种选择是简单地从您自己的 .net 代码中发出 cookie 集合。就像是:

foreach(HttpCookie cookie in request.Cookies) {
  Response.Write(String.Format("{0} = {1}", cookie.Name, cookie.Value));
}

看看会发生什么。

于 2013-03-01T17:04:10.993 回答
0

我尝试了另一种方法,通过创建一个返回最新 cookie 出现的方法,这样我总能得到正确的数据。

该方法期望从 Request 中收集 cookie,以及搜索到的 cookie 的名称,并返回最新的票证(通常加密的信息)

private static FormsAuthenticationTicket GetLatestCookie(HttpCookieCollection cookies, string cookieName) {
    var cookieOccurrences = new List<FormsAuthenticationTicket>();

    for (int index = 0; index < cookies.Count; index++) {
        if (cookies.GetKey(index) == cookieName) {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookies[index].Value);
            cookieOccurrences.Add(ticket);
        }
    }

    DateTime oldestTime = DateTime.MinValue;
    FormsAuthenticationTicket oldestTicket = null;
    foreach (var formsAuthenticationTicket in cookieOccurrences) {
        if (formsAuthenticationTicket.Expiration > oldestTime) {
            oldestTime = formsAuthenticationTicket.Expiration;
            oldestTicket = formsAuthenticationTicket;
        }
    }

    return oldestTicket;
}
于 2017-01-27T13:47:22.217 回答