Extend another class to make custom class type HttpContext.User

364 views Asked by At

I am making a mock social media app in Visual Studio 2013, using c#, asp.net-mvc5, and entity framework 6. I am trying to add custom user authentication I have implemented the authentication in the web.config:

<authentication mode="Forms">
  <forms loginUrl="~/AppUsers/Login" timeout="3000" />
</authentication>

and made sure that the ActionResult creates a cookie on login

    [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" });
    }

But I am now stuck, whenever I try to check if HttpContext.User.Identity.IsAuthenticated, I get an error that says:

"An object reference is required for the non-static field, method, or property 'System.Web.HttpContext.User.get'"

Do I need to make my AppUser class extend an HttpContext class to make this error go away, or do I have to rewrite the whole class as it is?

 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; }
}
1

There are 1 answers

1
Mahmud Ahmad On BEST ANSWER

Making

HttpContext.User.Identity.IsAuthenticated

into

HttpContext.Current.User.Identity.IsAuthenticated

fixed the issue for me