0

I am doing the management of a user's account when necessary I can Lock a user's account in case they violate it. Or can be unlocked if required. I got an error like this. Where am I wrong, I use .Net Core 5 to build my program. Error: "An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object."

enter image description here

Interface

    public bool LockUser(string email);
    public bool UnlockUser(string email);

Repo

public bool LockUser(string email)
    {
        var userTask = _userManager.FindByEmailAsync(email);
        userTask.Wait();
        var user = userTask.Result;

        var lockUserTask = _userManager.SetLockoutEnabledAsync(user, true);
        lockUserTask.Wait();

        var lockDateTask = _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now);
        lockDateTask.Wait();

        return lockDateTask.Result.Succeeded && lockUserTask.Result.Succeeded;
    }

Controller

public ActionResult LockUser(string email)
    {
        if (!_userRepository.LockUser(email))
        {
            throw new ArgumentException("Error");
        }
        return RedirectToAction("Index");
    }
Dave
  • 156
  • 1
  • 1
  • 14
Huy Nguyen
  • 27
  • 7
  • i think you are getting null object in userTask ...try use ```await``` operator like ```var userTask = await _userManager.FindByEmailAsync(email)```. – Dave Mar 15 '21 at 11:55
  • `The 'await' expression can only be used in a method or lambda marked with the 'async' modifier` – Huy Nguyen Mar 15 '21 at 12:03
  • are you getting data in ```userTask``` variable ? – Dave Mar 15 '21 at 12:23
  • Yes, I tried it but it doesn't seem to work. – Huy Nguyen Mar 15 '21 at 12:25
  • You need to learn about async programming. If you're using .Wait(), you're most likely doing it wrong. That's a code smell. Instead of .Wait(), you need to `await` your method calls that return a Task or Task. And any method where you need to do that needs to be marked as async. And so forth, all the way up the call stack. ASP.NET Core MVC has support for async action methods, so there's really no excuse not to do it properly here. – mason Mar 15 '21 at 13:08
  • As for the NullReferenceException, have you read [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mason Mar 15 '21 at 13:09

1 Answers1

0

Please refer the following sample code, the UserRepository should like this, add the usermanager via the constructor parameter:

public interface IUserRepository
{
    public bool LockUser(string email);
    public bool UnlockUser(string email);
}

public class UserRepository : IUserRepository
{
    private readonly UserManager<IdentityUser> _userManager;
    public UserRepository(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    } 
    public bool LockUser(string email)
    {
        var userTask = _userManager.FindByEmailAsync(email);
        userTask.Wait();
        var user = userTask.Result;

        var lockUserTask = _userManager.SetLockoutEnabledAsync(user, true);
        lockUserTask.Wait();

        var lockDateTask = _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now);
        lockDateTask.Wait();

        return lockDateTask.Result.Succeeded && lockUserTask.Result.Succeeded;
    }

    public bool UnlockUser(string email)
    {
        //...
        throw new NotImplementedException();
    }
}

Then, add the service to the service container:

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddScoped<IUserRepository, UserRepository>(); 
    services.AddControllersWithViews();
}

Then, in the MVC controller:

   public class HomeController : Controller
    { 
        private readonly IUserRepository _userRepository;
        public HomeController(IUserRepository userRepository)
        { 
            _userRepository = userRepository;
        } 
        public IActionResult Index(int id)
        {  
            string email = "aa@hotmail.com";
            if (!_userRepository.LockUser(email))
            {
                throw new ArgumentException("Error");
            }
            return View();
        }

The debug screenshot like this:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30