.Net Core 3.1中的通用类中的会话变量

问题描述

我是Core和Razor页面的新手,来自Web窗体背景,我讨厌它! 我正在公司的Intranet页面上,当前登录的(Win Login)用户名称和位置显示在_Layout页面菜单的右上方。我的Active Directory中有一些sql sp,因此我可以将用户ID传递给我的sp,以获得全名,位置,安全组等。我创建了一个名为Common的类,我想在其中存储我的常见任务。我当前正在使用局部视图,该局部视图调用我的方法获取全名。在使用静态方法调用非静态方法之后,我可以正常工作了,但是我的问题是,我不想每次用户更改页面时都访问数据库,所以我想我应该存储我的姓名/位置/安全组值在会话变量中,并且仅在它们过期时才从数据库中重置它们。好像我没有跳过足够多的圈只是为了从部分页获取uid而不是能够直接在我的班级中访问它一样,我无法设置会话变量。我在启动配置tom allow会话中设置了正确的值。我没有使用MVC,只有Razor。我得到的错误是... CS0120非静态字段,方法属性'HttpContext.Session'需要对象引用 如何访问会话变量,还是有更好的方法来维护当前登录用户值?谢谢。我正在拔头发。

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

解决方法

您需要进入Controller才能直接使用HttpContext。否则,您需要使用IHttpContextAccessor

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

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