【问题标题】:Create Cookie ASP.NET & MVC创建 Cookie ASP.NET 和 MVC
【发布时间】:2017-01-16 08:17:12
【问题描述】:

我有一个非常简单的问题。我想在客户端创建一个由服务器创建的 cookie。 我发现很多 pages 描述了如何使用它 - 但我总是停留在同一点上。

我有一个DBController,当有对 DB 的请求时,它会被调用。

DBController的构造函数是这样的:

public class DBController : Controller
{
    public DBController()
    {
        HttpCookie StudentCookies = new HttpCookie("StudentCookies");
        StudentCookies.Value = "hallo";
        StudentCookies.Expires = DateTime.Now.AddHours(1);
        Response.Cookies.Add(StudentCookies);
        Response.Flush();
    }

    [... more code ...]

}

我在以下位置收到错误“对象引用未设置为对象的实例”:

StudentCookies.Expire = DateTime.Now.AddHours(1);

这是一种基本的错误信息。那么我忘记了什么基本的东西?

【问题讨论】:

  • 我怀疑 Response 在控制器构造函数中为空。稍后设置。在操作方法中尝试您的代码。
  • Ya @Jim 它在动作方法中工作

标签: c# asp.net asp.net-mvc cookies


【解决方案1】:

问题是您无法在控制器的构造函数中添加响应。 Response 对象尚未创建,所以它正在获取一个空引用,尝试添加一个添加 cookie 的方法并在 action 方法中调用它。像这样:

private HttpCookie CreateStudentCookie()
{
    HttpCookie StudentCookies = new HttpCookie("StudentCookies");
    StudentCookies.Value = "hallo";
    StudentCookies.Expires = DateTime.Now.AddHours(1);
    return StudentCookies;
}

//some action method
Response.Cookies.Add(CreateStudentCookie());

【讨论】:

    【解决方案2】:

    使用Response.SetCookie(),因为Response.Cookie.Add() 可以添加多个cookie,而SetCookie() 将更新现有的cookie。 所以我认为你的问题可以解决。

    public DBController()
    {
        HttpCookie StudentCookies = new HttpCookie("StudentCookies");
        StudentCookies.Value = "hallo";
        StudentCookies.Expires = DateTime.Now.AddHours(1);
        Response.SetCookie(StudentCookies);
        Response.Flush();
    }
    

    【讨论】:

    • 使用你的方法,'System.NullReferenceException' 发生在 Response.SetCookie(StudentCookies);
    • 参考Jim's 评论,您提供的代码不起作用
    【解决方案3】:

    您可以使用控制器的Initialize() 方法而不是构造函数。 在初始化函数中,Request 对象可用。我怀疑Responseobject 也可以采取同样的行动。

    【讨论】:

      【解决方案4】:

      使用

      Response.Cookies["StudentCookies"].Value = "hallo";
      

      更新现有的 cookie。

      【讨论】:

        猜你喜欢
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-08
        • 2019-12-15
        相关资源
        最近更新 更多