【问题标题】:asp.net is it possible to read the value of a cookie from a static class?asp.net 是否可以从静态类中读取 cookie 的值?
【发布时间】:2009-09-04 00:11:17
【问题描述】:

我有一个带有静态属性的 CurrentUser 类,其值在用户上次访问网站时存储在 cookie 中。我希望能够从这个类中读取 cookie 的值。可能吗?看起来 Request.Cookies 仅在网页中可用。我正在尝试做的简化版本是:

class CurrentUser
{
public static string MyField
            {

                get
                {
                    return Request.Cookies["MyField"];
                }

            }

}

这不起作用。我收到此错误消息:“名称'请求'在当前上下文中不存在'。

【问题讨论】:

    标签: asp.net cookies


    【解决方案1】:
    using System.Web;
    ...
    return HttpContext.Current.Request.Cookies["MyField"];
    

    【讨论】:

      【解决方案2】:

      看看 HttpContext.Current。它使您可以访问会话、响应、请求等...

      【讨论】:

        【解决方案3】:

        可以使用HttpContext.Current.Request.Cookies["MyField"].. 但我强烈建议您不要这样做,因为您无法对其进行测试。

        如果代码上下文是您 CurrentUser 问题的唯一解决方案,我建议直接使用 CodeContext 而不是 HttpContext,尽管需要一些机制。

        你能解释一下为什么不推荐 HttpContext

        我想 CurrentUser 应该是业务代码。如果您使用 HttpContext,您将依赖于 ASP.net 的生命周期。如果您必须对依赖 CurrentUser 的某些业务功能进行单元测试,则必须走完整的 http 请求路径。

        【讨论】:

        • 你能解释一下为什么不推荐 HttpContext.Current.Request.Cookies["MyField"]?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 1970-01-01
        • 2017-07-27
        • 2017-02-25
        • 2014-06-29
        相关资源
        最近更新 更多