在ASP.NET中的Response.Redirect中传递cookie [英] Passing cookies in Response.Redirect in ASP.NET

查看:373
本文介绍了在ASP.NET中的Response.Redirect中传递cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将ASP.NET中的Cookie传递到新URL时遇到问题。我像这样向响应添加cookie:

I'm having a problem passing cookies in ASP.NET to a new URL. I add cookies to the Response like so:

Response.Cookies.Add(new HttpCookie("Username", Username.Text));

然后我发出重定向:

Response.Redirect(returnURL);

在我重定向到的新页面上,cookie集合为空。我尝试像这样检索Cookie:

On the new page that I am redirected to, the cookie collection is empty. I try to retrieve a cookie like so:

Request.Cookies [ Username]。Value;

有人能想到为什么未通过Cookie的原因吗?

Can anyone think of why the cookies are not being passed?

编辑:

我忘记添加其他信息-在同一浏览器会话中的第二次尝试中,Cookie通过重定向正确传递。

Further info I forgot to add - on the second attempt within the same browser session, the cookies ARE passed correctly with the redirect.

编辑#2:我发现,如果我在重定向URL中使用 localhost而不是实际域名,则cookie会在首次登录时正确传递。因此,仅当重定向URL是实际的域名时,它才起作用。奇怪。

EDIT #2: I have found that if I use "localhost" instead of the actual domain name in the redirect URL, then the cookies are passed correctly on first login. So its only when the redirect URL is the actual domain name that it doesn't work. Strange.

推荐答案

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Request.QueryString["AcceptsCookies"] == null)
        {
            Response.Cookies["TestCookie"].Value = "ok";
            Response.Cookies["TestCookie"].Expires =
                DateTime.Now.AddMinutes(1);
            Response.Redirect("TestForCookies.aspx?redirect=" +
                Server.UrlEncode(Request.Url.ToString()));
        }
        else
        {
            Label1.Text = "Accept cookies = " +
                Server.UrlEncode(
                Request.QueryString["AcceptsCookies"]);
        }
    }
}

此链接将帮助您了解用C#读写cookie。

This link will help you understand reading and writing cookies in C#.

此外,此页面为如果您对VB比C#更熟悉,则很有用。

Also, this page would be useful in case you are familiar with VB more than C#.

这篇关于在ASP.NET中的Response.Redirect中传递cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆