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