1

I am building an ASP.NET MVC application and need to get and edit the current user logged in the application. I use the build in IdentityModel and coded a couple of get and edit methods on the AccountController in a similar way as presented here: How to get current user, and how to use User class in MVC5?

AccountController methods:

[NonAction]
public async Task<ApplicationUser> getCurrentUser(string userid)
{
    var user = (ApplicationUser)await UserManager.FindByIdAsync(userid);
    return user;
}

[NonAction]
public async Task<int> editCurrentUser(ApplicationUser user)
{
    await UserManager.UpdateAsync(user);
    return 1;
}

My problem is when I try to call them from another controller, in this case to update the balance attribute from the payments controller:

var currentUser = await Controllers.AccountController.getCurrentUser(User.Identity.GetUserId());

because AccountController getCurrentUser and editCurrentUser are not static I cannot access them from the class. Quite obvious, but where does the MVC application create an instance of AccountController and how do I access it?

Alternatively, a better approach to retrieve and modify the current user?

Community
  • 1
  • 1
nest
  • 1,385
  • 1
  • 15
  • 34

2 Answers2

1

There are a range of options here. Perhaps the most straightforward method for you is to make these methods, extension methods:

[NonAction]
public async Task<ApplicationUser> getCurrentUser(string userid)
{
    var user = (ApplicationUser)await UserManager.FindByIdAsync(userid);
    return user;
}

[NonAction]
public async Task<int> editCurrentUser(ApplicationUser user)
{
    await UserManager.UpdateAsync(user);
    return 1;
}

So create a class like:

public static class UserManagerExtensions
{
        public static async Task<ApplicationUser> getCurrentUser(this UserManager userManager, string userid)
        {
            var user = (ApplicationUser)await userManager.FindByIdAsync(userid);
            return user;
        }

        public static async Task<int> editCurrentUser(this UserManager userManager, ApplicationUser user)
        {
            await userManager.UpdateAsync(user);
            return 1;
        }
}

And then call those extensions methods from each controller. This would mean you inject into PaymentsController, a UserManager etc just like is done in AccountController.

Alternatively you could use ActionFilters, create a common base class for Accounts, Payments controller, or dependency injection.

rism
  • 11,932
  • 16
  • 76
  • 116
0

You shouldn't call getCurrentUser from controller. Why can't you call (ApplicationUser)await UserManager.FindByIdAsync(userid); directly? The better way - put your methods working with users in special class (service) and reference it in placec you need to call this methods.

Backs
  • 24,430
  • 5
  • 58
  • 85