0

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();
        }
    }
}

1
  • 2
    You need to read some of the tutorials on MSDN and learn about the miracles of dependency injection. To properly master Core, you must leave static behind. Commented Oct 5, 2020 at 21:07

1 Answer 1

3

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 ....
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this approach to get access to session data in helper class. I can access httpContext but can't access session. I am getting a very ugly exception for session: ((Microsoft.AspNetCore.Http.DefaultHttpContext)((Microsoft.AspNetCore.Http.HttpContextAccessor)_httpContext).HttpContext).Session = ((Microsoft.AspNetCore.Http.DefaultHttpContext)((Microsoft.AspNetCore.Http.HttpContextAccessor)_httpContext).HttpContext).Session threw an exception of type 'System.InvalidOperationException'
because session is not enabled for your application.
in ConfigureServices method of Startup.cs I have used services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(10); }); and in Configure method I have used app.UseSession(); But still no luck.
It is better to open a new question. Or I am on codementor, If you want I can help you there.

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.