C# 何时使用 Request.Cookies 而不是 Response.Cookies?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/573922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:49:24  来源:igfitidea点击:

When to use Request.Cookies over Response.Cookies?

c#asp.net

提问by GurdeepS

Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processing? Or is there more to it?

我是否在页面事件(例如加载)时使用响应,因为这是来自 ASP.NET 的响应,并且在按下按钮时使用请求,因为这是将要发送到 ASP.NET 进行处理的响应?或者还有更多吗?

回答by tvanfosson

In a web application the request is what comes from the browser and the response is what the server sends back. When validating cookies or cookie data from the browser you should use the Request.Cookies. When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.

在 Web 应用程序中,请求来自浏览器,响应是服务器发回的内容。当验证来自浏览器的 cookie 或 cookie 数据时,您应该使用 Request.Cookies。当您构建要发送到浏览器的 cookie 时,您需要将它们添加到 Response.Cookies。

回答by balexandre

They are 2 different things, one SAVES[Response], the other READS[Request]

它们是两种不同的东西,一种是SAVES[Response],另一种是READS[Request]

in a Cookie (informatics speaking) :) you save a small file for a period of timethat contains an object of the type string

在 Cookie 中(从信息学上讲):) 您将一个小文件保存一段时间,其中包含字符串类型的对象

in the .NET framework you save a cookiedoing:

在 .NET 框架中,你保存一个 cookie做:

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");

You wrote a cookie that will be available for one minute... normally we do now.AddMonth(1)so you can save a cookie for one entire month.

您编写了一个可使用一分钟的 cookie……通常我们现在这样做。AddMonth(1)以便您可以将 cookie 保存一整个月。

To retrieve a cookie, you use the Request (you are Requesting), like:

检索 cookie,您可以使用请求(您正在请求),例如:

HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");

Remember:

记住:

To Delete a Cookie, there is no direct code, the trick is to Savethe same Cookie Name with an Expiration date that already passed, for example, now.AddMinutes(-1)

要删除一个 Cookie,没有直接的代码,诀窍是使用已经过去的过期日期保存相同的 Cookie 名称,例如,now.AddMinutes(-1)

this will delete the cookie.

这将删除cookie。

As you can see, every time that the time of life of the cookie expires, that file is deleted from the system automatically.

如您所见,每次 cookie 的生命周期到期时,该文件都会自动从系统中删除。

回答by Guffa

The cookies comes from the browser in the Request.Cookies collection. That is where you read the cookies that was sent.

cookie 来自 Request.Cookies 集合中的浏览器。这是您读取发送的 cookie 的地方。

To send cookies back to the browser you put them in the Response.Cookies collection.

要将 cookie 发送回浏览器,请将它们放在 Response.Cookies 集合中。

If you want to delete a cookie, you have to tell the browser to remove it by sending the cookie with an expiration date that has passed. The browser is using the local time of the client computer so if you are using the server time to create a date, be sure to subtract at least one day to be sure that it has actually passed in the clients local time.

如果您想删除一个 cookie,您必须通过发送过期日期已过的 cookie 来告诉浏览器将其删除。浏览器正在使用客户端计算机的本地时间,因此如果您使用服务器时间来创建日期,请务必减去至少一天以确保它实际上已通过客户端本地时间。

回答by andleer

When writing a cookie, use Response but reading may depend on your situation. Normally, you read from Request but if your application is attempting to get a cookie that has just been written or updated and the round trip to the browser has not occured, you may need to read it form Response.

写入 cookie 时,请使用 Response,但读取可能取决于您的情况。通常,您从 Request 中读取,但如果您的应用程序试图获取刚刚写入或更新的 cookie 并且尚未发生到浏览器的往返,则您可能需要从 Response 中读取它。

I have been using this pattern for a while and it works well for me.

我已经使用这种模式有一段时间了,它对我来说效果很好。

public void WriteCookie(string name, string value)
{
    var cookie = new HttpCookie(name, value);
    HttpContext.Current.Response.Cookies.Set(cookie);
}


public string ReadCookie(string name)
{
    if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Response.Cookies[name];
        return cookie.Value;
    }

    if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Request.Cookies[name];
        return cookie.Value;
    }

    return null;
}

回答by Alex

When i create or update a cookie in .NET i normally do it to both the request and response cookie collection. That way you can be sure if you try to read the cookie further down the page request sequence it will have the correct information.

当我在 .NET 中创建或更新 cookie 时,我通常会对请求和响应 cookie 集合执行此操作。这样您就可以确定,如果您尝试在页面请求序列的下方进一步读取 cookie,它将获得正确的信息。

回答by Venkatx5

Andrew's Code gave an error in "AllKeys.Contains" Method. So I corrected a little..

安德鲁的代码在“AllKeys.Contains”方法中出现错误。所以我纠正了一点..

public void WriteCookie(string strCookieName, string strCookieValue)
    {
        var hcCookie = new HttpCookie(strCookieName, strCookieValue);
        HttpContext.Current.Response.Cookies.Set(hcCookie);
    }


    public string ReadCookie(string strCookieName)
    {    
        foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Response.Cookies[strCookie].Value;
            }
        }         

        foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Request.Cookies[strCookie].Value;
            }
        }

        return null;
    }