For every page requested, I need to check a cookie or create it if it's not there. If the cookie is there, I need to load up some info from the DB based on the contents of that cookie.
To do this I have created a base controller called AppController that my other controllers inherit from.
then I have something like this (so that the CurrentSessionValues object is available to 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
// e.g. logged in user id, cart id, etc
}
}
When I run this, I get this error in default.aspx:
An error occurred while creating a controller of type 'Mvc_Learn.Controllers.HomeController'.
If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor.
It breaks on Request.Cookies["MySiteCookie"]
Should I be doing this logic in some other way or another place?
Trick is that you don't have context in the constructor necessarily. Rather, you should override the Initialize method:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
// DO NOT forget to call the base
base.Initialize(requestContext);
//check request context for cookie and do your thang.
}
PS: for posterity, I should note why there is an error. The key part of the exception info is that an error took place while creating the controller, the parameterless constructor bit is a red herring in this case. The error which took place was a null reference exception to HttpContext.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With