-2

I am trying to display information of the current logged in user. In the AccountController, I added the following action method:

public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

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

    //.......

    public ActionResult Profile()
    {
        var userId = User.Identity.GetUserId();

        if(userId == null)
        {
            return RedirectToAction("Login", "AccountControler");
        }
        else
        {
            ApplicationUser user = _userManager.FindByIdAsync(userId).Result;

            return View(user);
        }
    }
}

However, I get the following exception:

Object reference not set to an instance of an object. _userManager was null

2

1 Answer 1

4

_userManager would be null unless you're assigning it somewhere (and in the code you've included, you're not).

Edit, to correspond to your edit

Ideally, pass a UserManager instance into your controller constructor and let dependency injection handle it. You'd register the service in your Startup.cs.

If you're not up for that, you might want to browse this site for questions where people are having similar problems. "Object reference not set to an instance of an object" isn't the problem, though. The problem is inside your UserManager getter.

Maybe GetOwinContext() isn't available. Check this question and similar ones: Can't get UserManager from OwinContext in apicontroller

Better Yet

Learn to use your debugger! Place a breakpoint in your method and step through until it breaks. Mouse over the variables and see which one is null when you expect it not to be.

1
  • userId gets the right value. _userManager is null. The rest is just generated code by Individual User Accounts feature
    – AlexandraP
    Nov 26, 2018 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.