嗨我试图检索我的会话值并将其用于_layout.cshtml,但每次我得到null异常(Object reference not set to an instance of an object.)
这里是我的代码。我究竟做错了什么。 layout.cshtml无法加载〜/ Views / Shared / _LayoutHome.cshtml布局。 beacouse它没有获得任何会话价值。
@{
if(HttpContext.Current.Session["LoggedUserType"].ToString() == "superadmin" && HttpContext.Current.Session["DEPTNM"].ToString() == "AlchemyAdmin")
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
else
{
Layout = "~/Views/Shared/_LayoutHome.cshtml";
}
}
这是我的控制器代码,我可以使用我的会话值。
[HttpPost]
public ActionResult Index(LoginModel model)
{
if (ModelState.IsValid)
{
if (DataAccess.LoginDAL.AdminIsValid(model.LOGINID, model.LOGINPW))
{
var result = (from n in db.AslUsercoDbSet
where n.LOGINID == model.LOGINID &&
n.LOGINPW == model.LOGINPW
select new
{
companyid= n.COMPID,
userid = n.USERID,
deptname= n.DEPTNM,
usertype = n.OPTP
}
);
foreach (var n in result)
{
Session["loggedCompID"] = n.companyid;
Session["loggedUserID"] = n.userid;
Session["LoggedDepartment"] = n.deptname;
Session["LoggedUserType"] = n.usertype;
}
FormsAuthentication.SetAuthCookie(model.LOGINID, true);
return RedirectToAction("Index", "Home");
}
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View();
}
我在这里添加了我的dataaccess图层代码。如果存在,则验证用户。
internal static bool AdminIsValid(string username, string password)
{
bool authenticated = false;
string query = string.Format("SELECT * FROM [AslUsercoes] WHERE LOGINID = '{0}' AND LOGINPW = '{1}'", username, password);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
da.Fill(ds);
SqlDataReader sdr = cmd.ExecuteReader();
authenticated = sdr.HasRows;
conn.Close();
return (authenticated);
}
答案 0 :(得分:0)
这取决于您如何为会话分配值。
Session [“LoggedUserType”] = value(块不能有using()语句。因为它会在这种情况下处理你的值对象。)
请参阅以下链接。
MVC 4 Persist Data throughout website
第二,
您需要用户全线(Html.ViewContext.HttpContext)
@{
if(Html.ViewContext.HttpContext.Current.Session["LoggedUserType"].ToString() == "superadmin" && Html.ViewContext.HttpContext.Current.Session["DEPTNM"].ToString() == "AlchemyAdmin")
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
else
{
Layout = "~/Views/Shared/_LayoutHome.cshtml";
}
}