Asp.net mvc cannot access cookies in base controller

For each page I request, I need to check the cookie or create one if it does not exist. If a cookie exists, I need to download some information from the database based on the contents of this cookie.

To do this, I created a base controller called AppController, which my other controllers inherit.

then I have something like this (so the CurrentSessionValues ​​object is available for all my controllers):

public MySession CurrentSessionValues; public ApplicationController() { if (Request.Cookies["MySiteCookie"] == null) { // create new Record in DB CurrentSessionValues = CreateMySession(); HttpCookie cookie = new HttpCookie("MySiteCookie"); cookie.Value = CurrentSessionValues.SessionID.ToString; Response.SetCookie(cookie); } else { // use the value in MySiteCookie to get values from the DB // eg logged in user id, cart id, etc } } 

When I run this, I get this error in default.aspx:

An error occurred while creating the controller of type 'Mvc_Learn.Controllers.HomeController'.

If the controller does not have a factory controller, make sure it is an unsigned public constructor.

It breaks into Request.Cookies ["MySiteCookie"]

Should I do this logic in some other way or in another place?

+4
source share
2 answers

The trick is that you have no context in the constructor. Rather, you should override the Initialize method:

 protected override void Initialize(System.Web.Routing.RequestContext requestContext) { //check request context for cookie and do your thang. } 

PS: for posterity, I must note why the error occurs. The key part of the exception information is that an error occurred while creating the controller, in this case the constructor bit without parameters is a red herring. The error that occurred was an exception to the HttpContext reference.

+9
source

Ensure that the HomeController has a dimensionless public constructor and verifies that the parent constructor of ApplicationController() called.

0
source

All Articles