【发布时间】:2019-07-21 21:37:35
【问题描述】:
我有一个用户登录然后它调用控制器。我在用户表中搜索电子邮件匹配并将其保存到用户变量中。但是当我尝试检查它是否是管理员用户时,权限列为空,它是一个空引用。
为什么用户不先或默认拉取所有列数据,我在数据库中检查并且permissionId在那里,但是当我检查所述行的值时将其拉为null。
我真的很清楚,这是我的第一个更大的项目,也是我第一次在谷歌上搜索似乎找不到答案。
这是实体:
用户:
public class User
{
public int UserId { get; set; }
[Column(TypeName = "VARCHAR(100)")]
[StringLength(100)]
[Required]
public string FirstName { get; set; }
[Column(TypeName = "VARCHAR(100)")]
[StringLength(100)]
[Required]
public string LastName { get; set; }
[Column(TypeName = "VARCHAR(100)")]
[StringLength(250)]
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string UserName { get; set; }
//The user can have many posts
public List<Post> Post { get; set; }
public virtual Permissions Permissions { get; set; }
}
权限:
public class Permissions
{
public int PermissionsID {get; set;}
[Required]
public bool admin { get; set; }
[Required]
public bool StandUser { get; set; }
//Many Users can have a permission, this makes the foreign key for the Post Table.
public List<User> User { get; set; }
}
这是登录后的控制器:
[HttpPost]
public IActionResult Login(LoginViewModel loginViewModel)
{
//We're grabbing the plain text password so we can hash it later.
loginViewModel.plainTextPassword = loginViewModel.user.Password;
//Searching for the users emaill address and gathering the user information.
User userInfo = _context.Users.FirstOrDefault(x => x.Email == loginViewModel.user.Email);
//if the user information is null, then we don't have the user information.
if (userInfo == null)
{
ViewBag.Error = "Sorry, but we couldn't log you in.";
return View();
}
else if (Hashing.Confirm(loginViewModel.plainTextPassword, userInfo.Password, Supported_Ha.SHA256))
{
//Were building the user session information
HttpContext.Session.SetString("UserFirstName", userInfo.FirstName);
HttpContext.Session.SetString("UserLastName", userInfo.LastName);
HttpContext.Session.SetInt32("UserUserId", loginViewModel.user.UserId);
if (userInfo.Permissions.admin == true)
{
HttpContext.Session.SetString("IsAdmin", "true");
}
else
{
HttpContext.Session.SetString("IsAdmin", "false");
}
ViewBag.IsAdmin = HttpContext.Session.GetString("IsAdmin");
ViewBag.SessionUserName = HttpContext.Session.GetString("UserFirstName");
return RedirectToAction("Index");
}
ViewBag.Error = "Sorry, but we couldn't log you in.";
return View("Index");
}
我希望 userInfo 的所有行都不为空,所以我稍后可以检查用户是否是管理员。
【问题讨论】:
-
导航属性(我假设
Permissions是这样的)需要明确包含_context.Users.Include(user => user.Permissions).FirstOrDefault(user => user.Email == loginViewModel.user.Email);
标签: c# entity-framework model-view-controller