0

I have this api controller that I use to authenticate my users

public class UsersData : Controller
    {
        private ApplicationDbContext dbContext = new ApplicationDbContext();
        private readonly LoggingController logger = (LoggingController)LogManager.GetCurrentClassLogger(typeof(LoggingController));
        private ApplicationUserManager _userManager;


        public UsersData()
        {
            logger.ConfigureLogger();
            logger.SetApplicationName(ConfigurationManager.AppSettings["AppName"]);
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        public bool AuthenticateUser(LoginDTO Input)
        {
            var user = dbContext.Users.SingleOrDefault(u => u.UserName == Input.Email);
            var passwordHash = UserManager.PasswordHasher.HashPassword(Input.Password);
            if(passwordHash == user.PasswordHash)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

However, when I access it via Postman at http://localhost:9000/api/authentication?username=user@onae.com&password=1, it returns this error $exception {"Object reference not set to an instance of an object."} System.NullReferenceException

Am I doing something wrong? It looks like the issue is in the UserManager that is returning null? But I'm not sure how I can fix this.

Edit

return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

This line is the one that returns null. How do I reinitialise the user manager? I thought I did it already.

halfer
  • 19,824
  • 17
  • 99
  • 186
JianYA
  • 2,750
  • 8
  • 60
  • 136
  • If you can, you should debug your code and figure out which object in the code is NULL and make sure that it is initialized properly or handle the exception properly. – Chetan Aug 15 '18 at 08:44
  • I have debugged and this line is the one that returns null. return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); – JianYA Aug 15 '18 at 09:52
  • Looks like `HttpContext.GetOwinContext()` is returning null – Chetan Aug 15 '18 at 13:18
  • @ChetanRanpariya yeah. How do I authenticate a user via api then? – JianYA Aug 16 '18 at 02:16

0 Answers0