MotleyDrew
MotleyDrew

Reputation: 51

Session variable in .Net Core 3.1 in common class

I'm new to Core and Razor pages, coming from a Web Forms background, and I hate it! I'm working on a company Intranet page where the currently logged in (Win Login) user's name and location appear in the top right of the menu in the _Layout page. I have some SQL sp's that hit our Active Directory, so I can pass the user id to my sp to get the full name, location, security groups, etc. I created a class called, Common, where I want to store my common tasks. I'm currently using a partial view that calls my method to get the full name. After having a static method call a non-static method, I got that part working, but my problem is, I don't want to hit the database every time the user changes pages, so I thought I would store my name/location/security group values in session variables, and only reset them from the database if they are expired. As if I didn't jump through enough hoops just to get the uid from a partial page instead of being able to access it directly in my class, I am not unable to set the session variables. I've set the right values in the startup config tom allow session. I'm not using MVC, just Razor. The error I get is... CS0120 An object reference is required for the non-static field, method, or property 'HttpContext.Session' How do I access the session vars, or is there a better way to maintain the currently logged in user values? Thanks. I'm pulling my hair out.

//Partial view to pass the currently logged on user to a class method to get full name
@Common.getUser2(User.Identity.Name)

//My Common class that pprocesses the uid and returns the user's full name
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace Intranet3
{

    public class Common
    {
        //Static method to get user info.
        public static string getUser2(string uid)
        {
            Common foo = new Common();
            string currentUser = foo.getUserNonStatic(uid);
            //This next line is where the code fails
            HttpContext.Session.SetString(usrFullName, currentUser);
            return currentUser.ToString();
        }

        //Non-static method to get user info from the static getUser method. 
        public string getUserNonStatic(string uid)
        {
            string currentUser = "";

            using (SqlConnection con = new SqlConnection(@"Data Source=<MyDB;Initial Catalog=TCF_IS;Persist Security Info=True;User ID=webuser;Password=*******"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "EXEC [sp_ad_get_single_user] '" + uid + "'";
                    cmd.Connection = con;
                    con.Open();
                    cmd.Parameters.AddWithValue("@UserName", uid);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        currentUser = dr["displayName"].ToString();
                    }
                    con.Close();
                    //return empResult;
                }
            }
            return currentUser.ToString();
        }
    }
}

Upvotes: 0

Views: 2081

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

you need to be inside Controller in order to use HttpContext directly. Otherwise you need to use IHttpContextAccessor

public class Common
{
    private IHttpContextAccessor _accessor;
 
    public Common(IHttpContextAccessor accessor ){
        _accessor = accessor;
    }

    public void MyFunc(){
        //here you can access HttpContext
        _accessor.HttpContext.Session ....
    }
}

Upvotes: 3

Related Questions