Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建Cookie ASP.NET&;MVC_C#_Asp.net_Asp.net Mvc_Cookies - Fatal编程技术网

C# 创建Cookie ASP.NET&;MVC

C# 创建Cookie ASP.NET&;MVC,c#,asp.net,asp.net-mvc,cookies,C#,Asp.net,Asp.net Mvc,Cookies,我有一个非常简单的问题-我想在客户端创建一个cookie,它是由服务器创建的。 我发现了很多关于如何使用它的描述,但我总是停留在同一点上 我有一个DBController,当有对DB的请求时会调用它 DBController的构造函数如下所示: public class DBController : Controller { public DBController() { HttpCookie StudentCookies = new HttpCookie("St

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

我有一个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 ...]

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


这是一种基本的错误消息-那么我忘记了什么样的基本信息?

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

公共数据库控制器() { HttpCookie StudentCookies=新的HttpCookie(“StudentCookies”); StudentCookies.Value=“你好”; StudentCookies.Expires=DateTime.Now.AddHours(1); 回答:SetCookie(StudentCookies); Response.Flush(); }
问题是您无法在控制器的构造函数中添加响应。响应对象尚未创建,因此它将获得空引用,请尝试添加用于添加cookie的方法并在操作方法中调用它。像这样:

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());

您可以使用控制器的
Initialize()
方法而不是构造函数。 在初始化功能中,
请求
对象可用。我怀疑可以对
响应
对象执行相同的操作。

使用

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

更新现有cookie。

我怀疑控制器构造函数中的
Response
为空。以后再定。在action方法中尝试您的代码。Ya@Jim它在action方法中工作也使用您的方法“System.NullReferenceException”出现在Response.SetCookie(StudentCookies)行中;参考注释,您提供的代码不起作用
Response.Cookies["StudentCookies"].Value = "hallo";