【问题标题】:Checking Cookie for Value in ASP.NET results in an Object Reference Null Exception在 ASP.NET 中检查 Cookie 的值会导致对象引用空异常
【发布时间】:2016-05-26 21:24:40
【问题描述】:

当我尝试访问 cookie 时,出现以下异常:

对象引用未设置为对象的实例。

这是有问题的行:

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

控制器

[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);

        }

【问题讨论】:

  • @GeorgeStocker 错误发生在实际的 if 语句中:if (Request.Cookies["selectBoxValue"].Value != null)。似乎没有要评估的 cookie 值。没有设置cookie值。这有帮助吗?
  • 我不确定这是否是问题所在,但是现在我知道这是问题所在,您有什么解决方法吗?是否可以将 selectBoxValue 设置为默认值?这样它可能是一个对象的实例?

标签: c# asp.net entity-framework cookies


【解决方案1】:

您的错误是因为该链中的某些内容不存在:

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

检查事项:

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

您很可能没有传入名为selectBoxValueRequest cookie。因为selectBoxValue(来自它的名字)听起来像是你的表单本身的东西,我很好奇你为什么要检查一个cookie?如果它是来自上一页的持久值(不是向服务器发送请求的那个),则称它为比 selectBoxValue 更直观的名称。

了解有关如何编写 cookie 和读取 cookie 的更多信息;看到这个Stack Overflow answer

如果您希望用户拥有一个名为 selectBoxValue 的 cookie,而他们没有,那么您就有一个特定的问题:无论您在哪里设置该 cookie,它都不会在 Response 中发送给用户。

如果您对此感到满意(即,某些代码路径期望该 cookie 而其他代码路径不期望该 cookie),那么如果该 cookie 不存在,您可以将您正在使用的对象设置为一个合理的值:

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

您的代码也有一些问题:

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);
}

为什么你创建一个cookie只是为了不使用它?

仅当您要将其发送到某个地方时才会创建 Cookie。所以在这里你应该写这样的东西:

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.

}

【讨论】:

    【解决方案2】:

    您正在检查您的 cookie 的值是否为空,它可能是也可能不是。如果尚未设置 cookie,则 cookie 本身为 null,这意味着如果您尝试访问 cookie 的值,则会出现异常。

    这是您需要检查的代码 sn-p。

    //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
        }
    }
    

    要设置 cookie,您可以在控制器操作中使用 Response.SetCookie() 方法。这是一个简单的例子:

    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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2021-08-30
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多