Search code examples
asp.net-mvcasp.net-identityidentity

userManager.FindById(userId) throws ArgumentNullException


I know this question has already been asked, but none of the answers seem to fit.

I have set up a standard asp.net MVC 5 web application using Individual Accounts.

I have not changed anything in the AccountController. I just created a new Controller, and in the Index action method the two first lines are:

var userId = User.Identity.GetUserId();
var user = userManager.FindById(userId);

I also declare an ApplicationUserManager:

private ApplicationUserManager userManager;

userManager.FindById(userId) throws the ArgumentNullException.

It all looks like this:

[Authorize]
public class WishlistController : Controller
{
    private ApplicationDbContext db;
    private ApplicationUserManager userManager;

    // GET: Wishlist
    public ActionResult Index()
    {
        var userId = User.Identity.GetUserId();
        var user = userManager.FindById(userId); // This line throws the exception

        db = new ApplicationDbContext();

        return View(db.Wishlists.ToList().Where(wishlist => wishlist.User.Id == user.Id));
    }

Edit

Name of question changed since I discovered that User.Identity.GetUserId() does not return null anyway. It returns a nice long string as it should.

I still got the problem with FindById(userId).


Solution

  • I would expect the code you've posted (at your 4th revision) to fail at the line indicated, but I would expect it to raise a NullReferenceException rather than an ArgumentNullException. You're declaring an ApplicationUserManager variable, but not initializing it. So, when you attempt to call a method on it, that should fail.

    I'm not sure why you want to retrieve the User object anyway. All you're doing with that User object is retrieving the user ID - which is exactly what you used to fetch the User in the first place. Why not just use the user ID directly? In which case, you don't even need the ApplicationUserManager.