Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc can't access cookie data in base controller

Tags:

asp.net-mvc

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?

like image 521
Nils Avatar asked Jan 23 '23 06:01

Nils


1 Answers

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.

like image 112
Wyatt Barnett Avatar answered Jan 25 '23 20:01

Wyatt Barnett