C# 从静态类编写cookie

C# 从静态类编写cookie,c#,asp.net,C#,Asp.net,我的解决方案中有一个静态类,基本上是使用helper/ultility类 其中我有以下静态方法: // Set the user public static void SetUser(string FirstName, string LastName) { User NewUser = new User { Name = String.Format("{0}{1}", FirstName, LastName) }; HttpCookie UserN

我的解决方案中有一个静态类,基本上是使用helper/ultility类

其中我有以下静态方法:

// Set the user
    public static void SetUser(string FirstName, string LastName)
    {
        User NewUser = new User { Name = String.Format("{0}{1}", FirstName, LastName) };
        HttpCookie UserName = new HttpCookie("PressureName") { Value = NewUser.Name, Expires = DateTime.Now.AddMinutes(60) };       

    }
HttpContext.Current.Response.Cookies.Add(UserName);
User是一个简单的类,包含:

  String _name = string.Empty;

    public String Name
    {
        get { return _name; }
        set { _name = value; }
    }
在我尝试编写cookie“PressureName”并从NewUser.Name中插入值之前,一切都正常。从单步执行代码来看,cookie似乎从未被写入


我是不是犯了一个明显的错误?我在c#方面仍然非常业余,非常感谢您的帮助。

创建cookie对象不足以将其发送到浏览器。您还必须将其添加到响应对象中

由于您使用的是静态方法,因此无法直接访问页面上下文,它是
Response
属性。使用
Current
属性从静态方法访问当前页面的上下文:

// Set the user
    public static void SetUser(string FirstName, string LastName)
    {
        User NewUser = new User { Name = String.Format("{0}{1}", FirstName, LastName) };
        HttpCookie UserName = new HttpCookie("PressureName") { Value = NewUser.Name, Expires = DateTime.Now.AddMinutes(60) };       

    }
HttpContext.Current.Response.Cookies.Add(UserName);

谢谢你,先生,我感谢你的帮助!