【发布时间】:2013-07-10 03:16:52
【问题描述】:
如何使用User.Identity.Name 在控制器之外的类中工作?
我只是在课堂上这样使用
private readonly static string sLogon = HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1);
它在 IIS 7.5 生产服务器上重新运行 null 引用,即使它在开发服务器上也可以工作。
在这里,我使用了一些替代方法。
- 起初我使用
Environment.Username。这在开发中效果很好。但不是在发布之后。因为然后Environment.Username产生应用程序运行的应用程序池的名称。如here 所述。 -
Controller.User.Identity.Name用于在控制器中获取所需的用户名,在发布前和发布后效果很好。但它不能在 Class .cs 的上下文中使用。 -
System.Web.HttpContext.Current.User.Identity.Name产生空引用。 -
System.Security.Principal.WindowsIdentity.GetCurrent().Name工作方式与Environment.Username相同
您对如何使用它有任何想法吗?谢谢
更新
根据环境,如果我得到登录ID,我可以从Employee表中获取EmployeeID,Email等员工信息。例如:我有一个类(在控制器之外)从 Employee 表中获取 Employee ID 以便像这样访问。
string EmployeeID = new EmployeeService().EmployeeID();
private readonly static string sLogon = HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1);
public string EmployeeID()
{
var employee = new Common().Employee();
string sID = (from e in employee
where (e.LogonID ?? "N/A").ToLower().Contains(sLogon.ToLower())
select e.EmployeeID).FirstOrDefault();
return sID;
}
【问题讨论】:
-
您能大致了解您要做什么吗?假设您正在尝试获取当前登录用户的用户名,您何时尝试使用它? IE。你在哪里使用这个“控制器之外的类”?
-
@RowanFreeman 我刚刚更新了问题,拜托
-
类什么时候被调用?是在调用 Action 之前、期间还是之后?
-
是否为 Windows 身份验证正确设置了生产服务器?是否禁用匿名身份验证?
标签: asp.net-mvc asp.net-mvc-4 iis-7.5 windows-authentication