2
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)

4 Answers 4

6

I think you intend to look at the current HttpContext. For this, you need to add a dependency for IHttpContextAccessor to your controller constructor, then use the HttpContext property of that interface in your action method to access the current context.

You may have to register

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

in your Startup.cs, depending on whether or not you already have this service added by other common services that may depend on it.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm using the httpcontext in my controller by only adding the using statement: using Microsoft.AspNetCore.Http; I created a class to simplify the code in the controller methods and in the class is where I'm having trouble using the HttpContext.
You are statically referencing the class HttpContext by using that method, which is causing that error. You need an instance of HttpContext, not the static class reference.
I implemented the IHttpContextAccessor and registered the service. I literally get the same exact error if I make the function static. If it's not static, I can't access the method of the class inside the controller where I'm calling it from.
@tocoolforscool : were you able to find a soln for this. I am also facing same issue
2

I'm getting this error

You can't access an instance member from a static member. You may want to read up on static members.

The error disappears if I don't declare the method as static

Yes, because an instance method can access an instance field.

however from my controllers I can't access the method UserAccount.SignIn if the method ISN'T declared as static.

Sure they can - but they need an instance:

private UserAccount _userAccount;
ControllerConstructor(IHttpContextAccessor accessor)
{
  _userAccount = new UserAccount(accessor);
}

...
// Inside an action method:
await _userAccount.SignIn(user);

If I declare the variable _httpContextAccessor [as static], all errors go away

Yes, because a static method can access a static field.

but I get a null reference exception on the await statement again.

Because the static field is never initialized.

Comments

0

My solution:

Register the HttpContextAccessor in Startup:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Then to get the current user:

using (var scope = host.Services.CreateScope())
{
    var currentContext = scope.GetService<IHttpContextAccessor>();
    return currentContext.HttpContext.User;
}

2 Comments

what is "host" and can it be accessed outside of a controller?
@rdans I don't think so
-1

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.

1 Comment

This doesn't really answer the question, only getting access to it in view, not in code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.