Seb
Seb

Reputation: 183

Checking Cookie for Value in ASP.NET results in an Object Reference Null Exception

When I attempt to access a cookie, I get the following exception:

Object reference not set to an instance of an object.

This is the line in question:

if (Request.Cookies["selectBoxValue"].Value != null)

Controller

[Authorize]
        public ActionResult Index()
        {
            if (Request.Cookies["selectBoxValue"].Value != null)
            {
                HttpCookie groupId = new HttpCookie("selectBoxValue");
                groupId = Request.Cookies["selectBoxValue"];

                // Collect all comments connected to current group
                int t = Convert.ToInt32(groupId.Value);
                pv.ListofComments = db.Comments.Where(dp => dp.GroupID == t).ToList();

                // Show only groups connected to current user
                var CurrentUser = User.Identity.GetUserId();
                var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == CurrentUser).Select(gr => gr.GroupId).ToList();
                pv.GroupList = db.Groups.Where(g => groupUser.Contains(g.Id));
                return View(pv);

        }

Upvotes: 3

Views: 4140

Answers (2)

George Stocker
George Stocker

Reputation: 57872

Your error is because something in that chain is not there:

if (Request.Cookies["selectBoxValue"].Value != null)

Things to check:

var myCookie = Request.Cookies["selectBoxValue"];
myCookie!= null; 
myCookie.Length > 0;

Most likely you don't have a cookie coming in on the Request that's called selectBoxValue. Since selectBoxValue (from its name) sounds like it's something on your form itself, I'm curious as to why you'd be checking a cookie for it? If it's a persisted value from a previous page (not the one that sent the Request to the server), then call it something more intuitive than selectBoxValue.

To learn more about how to write a cookie and to read a cookie; see this Stack Overflow answer.

If you expect the user to have a cookie called selectBoxValue and they don't, then you have a specific issue: wherever you're setting that cookie, it's not getting sent to the user in the Response.

If you are OK with that (that is, some codepaths expect that cookie and others do not) then you can set the object you're playing with to a sane value if that cookie doesn't exist:

int defaultGroupId = 1;
var obj = Request.Cookies["selectBoxValue"] ?? defaultGroupId;

Your code also has some issues:

if (Request.Cookies["selectBoxValue"].Value != null)
{
  HttpCookie groupId = new HttpCookie("selectBoxValue"); //why create one?
  groupId = Request.Cookies["selectBoxValue"];

  // Collect all comments connected to current group
  int t = Convert.ToInt32(groupId.Value);
}

Why are you creating a cookie only not to use it?

A Cookie is only meant to be created if you're going to send it somewhere. So here you should write something like:

int defaultGroupId = 1;
int groupId = defaultGroupId;
if (Request.Cookies["selectBoxValue"] != null) {
    var parsed = Int.TryParse(Request.Cookies["selectBoxValue"].Value, out groupId);
 if (!parsed) {
   // the incoming cookie value wasn't an integer or couldn't be parsed to integer. In this case do you want to set it to an appropriate value (say whatever comes out of your query?
 }
//At this point you either have a valid `groupId` or you have your `defaultGroupId` so you can use `groupId` normally.

}

Upvotes: 2

Lars Kristensen
Lars Kristensen

Reputation: 1495

You are checking if the value of your cookie is null, which it may or may not be. If the cookie hasn't been set yet, then the cookie itself is null, which means you get an exception if you tryto access the value of the cookie.

Here's a code snippet of what you need to check.

//retrieve the cookie
var cookieSelectBoxValue = Request.Cookies["selectBoxValue"];

//Check if the cookie itself is null
if(cookieSelectBoxValue != null)
{
    //Retrieve the value of the cookie
    var cookieValue = cookieSelectBoxValue.Value;

    //Check if the value of the cookie is null
    if(cookieValue!= null)
    {
        //The rest of your logic goes here
    }
}

To set the cookie, you can use the Response.SetCookie() method in your Controller Action. Here's a quick example:

public ActionResult Index()
{
    if (Request.Cookies["selectBoxValue"] != null)
    {
        var cookie = new HttpCookie("selectBoxValue")
        {
            Expires = DateTime.Now.AddYears(1),
            Value = "CookieValueGoesHere"
        };
        Response.Cookies.Add(cookie);
    }
    return View("Index");
}

Upvotes: 0

Related Questions