Create Cookie ASP.NET & MVC

The problem is you cannot add to the response in constructor of the controller. The Response object has not been created, so it is getting a null reference, try adding a method for adding the cookie and calling it in the action method. Like so:

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

Use

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

to update existing cookie.


Use Response.SetCookie(), because Response.Cookie.Add() can add multiple cookies, whereas SetCookie() will update an existing cookie. So I think your problem can be solved.

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

You could use the Initialize() method of the controller instead of the constructor. In the initialize function the Request object is available. I suspect that the same action can be taken with the Responseobject.