scgough
scgough

Reputation: 5252

.NET Core 2.1 - Accessing Config/usermanager in a static helper

I've recently moved from MVC5 over to .NET Core 2.1 (MVC). Can anyone help me with this please.

I have my ApplicationUser and I've extended the model/table to store the user's FirstName.

In the View, I want to be able to output the current user firstname value. User in the view is a ClaimsPrincipal so I need to go off to the DB to grab the value I need or access UserManager to get it.

Now, I know I can get that in the controller but I don't want to have to create a JQuery call to grab it every time I need it.

What I do want is to be able to access it server side, ideally via a static helper class.

In the MVC5 I'd have a helper to do the job no problem. Something like this for example:

public static string GetCurrentUserFirstName()
{
    string _usrRef = HttpContext.Current.User.Identity.GetUserId();
    var user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(_usrRef);

    return user.FirstName;
}

However, .NET Core doesn't work that way.

In a controller I could say:

var user = await _userManager.GetUserAsync(User);
string firstName = user.FirstName;

or I could go off to the DB via a call using Dapper w/ my connection string.

I can't inject the UserManager or ConnectionStrings into the helper via the constructor as it is static.

Is there a way to access either of those in this static helper?

It's the little changes that get you the most!

Upvotes: 1

Views: 836

Answers (1)

scgough
scgough

Reputation: 5252

Thanks to @Kirk Larkin - I've found the solution.

I have to admit, it feels a little more convoluted having to pass things around to gain access to them but this is a good, working solution.

The View:

@using Microsoft.AspNetCore.Identity
@using MyApplication.Helpers

@inject UserManager<ApplicationUser> UserManager

<div>
    @await MyHelper.GetLoggedInUserFirstName(UserManager, User)
</div>

The MyHelper file:

public static async Task<string> GetLoggedInUserFirstName(UserManager<ApplicationUser> userManager, ClaimsPrincipal user)
{
    string output = "";

    try
    {
        var currentUser = await userManager.GetUserAsync(user);
        if(currentUser!=null)
        {
            output = currentUser.FirstName ?? currentUser.Email;
        }
    }
    catch(Exception e) { }

    return output;
}

Upvotes: 2

Related Questions