【发布时间】:2021-01-20 17:52:06
【问题描述】:
我是 Core 和 Razor 页面的新手,来自 Web 表单背景,我讨厌它! 我正在处理公司 Intranet 页面,当前登录(Win Login)用户的名称和位置出现在 _Layout 页面的菜单右上角。我有一些命中我们的 Active Directory 的 SQL sp,所以我可以将用户 ID 传递给我的 sp 以获取全名、位置、安全组等。我创建了一个名为 Common 的类,我想在其中存储我的常见任务.我目前正在使用调用我的方法来获取全名的局部视图。在有一个静态方法调用一个非静态方法之后,我得到了那部分工作,但我的问题是,我不想每次用户更改页面时都访问数据库,所以我想我会存储我的姓名/位置/会话变量中的安全组值,并且只有在它们过期时才从数据库中重置它们。好像我没有跳过足够多的圈子只是为了从部分页面获取 uid 而不是能够直接在我的类中访问它,我无法设置会话变量。我已经在启动配置 tom 允许会话中设置了正确的值。我没有使用 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();
}
}
}
【问题讨论】:
-
你需要阅读MSDN上的一些教程,了解依赖注入的奇迹。要正确掌握 Core,您必须留下
static。
标签: .net asp.net-core session-variables razor-pages httpcontext