我正在使用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时,我都会收到一条错误消息:
&#34;非静态字段,方法或属性需要对象引用“System.Web.HttpContext.User.get&#39;&#34;
我是否需要让我的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; }
}
答案 0 :(得分:0)
制作
HttpContext.User.Identity.IsAuthenticated
到
HttpContext.Current.User.Identity.IsAuthenticated
为我解决了这个问题