Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Cookie ASP.NET & MVC

I have a quite simple problem. I want to create a cookie at a Client, that is created by the server. I've found a lot of pages that describe, how to use it - but I always stuck at the same point.

I have a DBController that gets invoked when there is a request to the DB.

The DBController's constructor is like this:

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 ...]  } 

I get the Error "Object reference not set to an instance of an object" at:

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

This is a kind of a basic error message. So what kind of basic thing I've forgot?

like image 756
yesfabime Avatar asked Sep 08 '16 11:09

yesfabime


People also ask

Can an API set a cookie?

set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL.

How cookies are activated using ASP?

asp file, ASP begins a new session using the same cookie. The only time a user receives a new SessionID cookie is when the server administrator restarts the server, thus clearing the SessionID settings stored in memory, or the user restarts the Web browser.

How do I set cookies in Web API?

Cookies in Web API To add a cookie to an HTTP response, create a CookieHeaderValue instance that represents the cookie. Then call the AddCookies extension method, which is defined in the System. Net. Http.


1 Answers

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()); 
like image 99
James Ralston Avatar answered Oct 04 '22 05:10

James Ralston