Home > front end >  Object reference is required for HttpContext
Object reference is required for HttpContext

Time:10-25

Beginner to C# here.

I am trying to return only the number of users in the same facility as the current user (unless that user is a manager).

I am getting a red line under HttpContext.User on the 2nd and 3rd lines that says

An object reference is required for the non-static field, method, or property 'HttpContext.User'

I've tried researching this and none of those solutions, such as making the method static or calling it via System.Web.HttpContext.User have worked for me.

private int GetUsersforFacility(ICollection<ApplicationUserRole> Users)
{
     int userFacilityID = (int)HttpContext.User.GetFacilityId();
     bool manager = HttpContext.User.IsManager();

     if (!manager)
     {
          return Users.Where(user => user.FacilityID == userFacilityID).Count; 
     }

     return Users.Count;
}

Any suggestions would be appreciated.

CodePudding user response:

HttpContext inside the controller is property inherited from ControllerBase and if you use it outside the controller HttpContext is just a class so only static members of it can be accessed.

In order to access it you have to pass through or inject HttpContext down the line.

  • Related