-2

I am trying to build a user helper for core 2.2 to make it easier to get the current users information.

I keep getting back an object reference error on this current code

private static HtmlHelper _helper;

    public UserHelper(HtmlHelper helper)
    {
        _helper = helper;
    }

    public static IIdentity GetUserId()
    {
       var userIdentity = _helper.ViewContext.HttpContext.User.Identity;

       return userIdentity;
    }

I've searched and most solutions work only in the controller or not at all. How can i go about getting this to work in a class?

TheDizzle
  • 1,534
  • 5
  • 33
  • 76

1 Answers1

1

What you're attempting to do here doesn't make sense. First, you cannot inject HtmlHelper and second, you cannot rely on an injected value from a static method. The static method is called on the class, not the instance, and the ivar you're attempt to use is only available on an instantiated class instance.

You'd probably be better served by an extension. For example, you can do something like:

public static class HtmlHelperExtensions
{
    public static IIdentity GetUserId(this HtmlHelper helper)
    {
        var userIdentity = helper.ViewContext.HttpContext.User.Identity;

        return userIdentity;
    }
}

Then:

@Html.GetUserId()

Alternatively, you'd want to inject IHttpContextAccessor into your UserHelper, actually inject UserHelper to get an instance, and then have a non-static GetUserId method:

public class UserHelper
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserHelper(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public IIdentity GetUserId()
    {
        var userIdentity = _httpContextAccessor.HttpContext?.User.Identity;

       return userIdentity;
    }
}

Then, in your app's ConfigureServices:

services.AddHttpContextAccessor();
services.AddSingleton<UserHelper>();

In places like controller classes, you'd inject UserHelper just as anything else. In views, you can use:

@inject Namespace.To.UserHelper UserHelper
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444