Search code examples
c#asp.net-core-mvchttpcontext

Using HttpContext outside of a controller


public class UserAccount
{
  private readonly IHttpContextAccessor _httpContextAccessor;

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

  //Sign in
  public static async Task SignIn(dynamic user)
  {
    var claims = new[]
    {
      new Claim("UserID", user.ID.ToString()),
      new Claim(ClaimTypes.Role, "Baller")
    };

    var principal = new ClaimsPrincipal(
          new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

    await _httpContextAccessor.HttpContext.Authentication.SignInAsync("Cookies", principal);
  }
}

I'm getting this error from the await statement in the SignIn method: An object reference is required for the non-static field, method, or property "UserAccount._httpContextAccessor"

The error disappears if I don't declare the method as static, however from my controllers I can't access the method UserAccount.SignIn if the method ISN'T declared as static.

If I declare the variable _httpContextAccessor as so:

private static IHttpContextAccessor

rather than:

private readonly IHttpContextAccessor

all errors go away, but I get a null reference exception on the await statement again. (the _httpContextAccessor isn't set to an instance of an object)


Solution

  • You access the HttpContext like this:

    @if (Context.User.Identity.IsAuthenticated)
    {
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="User" asp-action="Logout">Logout</a>
            </li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li><a asp-area="" asp-controller="User" asp-action="Register">Register</a></li>
            <li><a asp-area="" asp-controller="User" asp-action="Login">Log in</a></li>
        </ul>
    }
    

    No directives or packages needed.