【发布时间】:2015-08-27 14:48:00
【问题描述】:
我正在使用 c#、asp.net-mvc5 和实体框架 6 在 Visual Studio 2013 中制作模拟社交媒体应用程序。我正在尝试添加自定义用户身份验证 我已经在 web.config 中实现了身份验证:
<authentication mode="Forms">
<forms loginUrl="~/AppUsers/Login" timeout="3000" />
</authentication>
并确保 ActionResult 在登录时创建一个 cookie
[HttpPost]
public ActionResult Login(string userName, string password)
{
AppUser user = null;
if (db.AppUser.Any(m => m.UserName == userName)) {
user = db.AppUser.Where(m => m.UserName == userName).First();
if (user.Password == password) {
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToAction("AppUserProfile", new { id = user.Id });
}
}
return RedirectToAction("Login", new { message = "Invalid Password" });
}
但是我现在卡住了,每当我尝试检查 HttpContext.User.Identity.IsAuthenticated 时,我都会收到一条错误消息:
“非静态字段、方法或属性‘System.Web.HttpContext.User.get’需要对象引用”
我是否需要让我的 AppUser 类扩展一个 HttpContext 类以消除此错误,还是必须按原样重写整个类?
public class AppUser
{
[Key]
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match")]
public string ConfirmPassword { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string EmailAddress { get; set; }
public virtual ICollection<UserPost> UserPosts { get; set; }
}
【问题讨论】:
标签: c# visual-studio-2013 asp.net-mvc-5 entity-framework-6 httpcontext