引发模型的 NullReferenceException 时的 RedirectToAction

RedirectToAction when NullReferenceException of the Model is raised

我有以下控制器方法

public ActionResult Details()
{
    try
    {
        Pacient pacientdp = new Pacient();
        if (pacientdp.PacientPrenume == null)
        {
            return RedirectToAction("Index", "Home");
        }
        var id = WebSecurity.GetUserId(User.Identity.Name);
        MedicalDBContext pacientContext = new MedicalDBContext();
        Pacient pacient = pacientContext.Pacients.FirstOrDefault(x => x.PacientID == id);
        return View(pacient);
    }
    catch (Exception ex)
    {
        return View("Error", new HandleErrorInfo(ex, "Home", "Index"));
    }
}

导航到详细信息视图时,如果我从控制器方法注释 if 部分,则会引发 NullReferenceException。有时会发生这种情况,但有时不会。这是我想要的行为。 所以我添加了 if 部分,所以当模型 属性(PacientPrenume) 为 null 时重定向到操作,但此方法每次都重定向到操作,即使模型不为 null。

通过上面的方法,无论pacientdp模型是什么(if是否为null)都会执行if块

只有当模型出现这个异常怎么办???

发现了问题,所以上下文模型实际上为我的模型设置了值,所以 pacientdp.PacientPrenume 属性 总是空的。下面是工作方法

            public ActionResult Details()
                {
                try
                    {
                    MedicalDBContext pacientContext = new MedicalDBContext();
                    var id = WebSecurity.GetUserId(User.Identity.Name);
                    if (pacientContext.Pacients.FirstOrDefault(x => x.PacientID == id) == null)
                        {
                        return RedirectToAction("Index", "Home");
                        }               
                        Pacient pacient = pacientContext.Pacients.FirstOrDefault(x => x.PacientID == id);
                        return View(pacient);
                    }
                catch (Exception ex)
                    {
                    return View("Error", new HandleErrorInfo(ex, "Home", "Index"));
                    }

                }