Asp.net mvc 如何使用User.Identity.Name在控制器之外的类中工作?

Asp.net mvc 如何使用User.Identity.Name在控制器之外的类中工作?,asp.net-mvc,asp.net-mvc-4,iis-7.5,windows-authentication,Asp.net Mvc,Asp.net Mvc 4,Iis 7.5,Windows Authentication,如何使用User.Identity.Name在控制器之外的类中工作? 我只是在课堂上这样用过 private readonly static string sLogon = HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1); 它在IIS7.5生产服务器上运行空引用,即使它在开发服务器上工作 在这里,我使用了一些替代方案

如何使用
User.Identity.Name
在控制器之外的类中工作? 我只是在课堂上这样用过

private readonly static string sLogon =  HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1);
它在IIS7.5生产服务器上运行空引用,即使它在开发服务器上工作

在这里,我使用了一些替代方案

  • 起初我使用了
    Environment.Username
    。这在开发中很有效。但不是在出版之后。因为
    Environment.Username
    会生成应用程序运行所在的应用程序池的名称。如上所述
  • Controller.User.Identity.Name
    用于在控制器中获取所需的用户名,在发布前和发布后都能很好地工作。但是它不能在Class.cs的上下文中使用
  • System.Web.HttpContext.Current.User.Identity.Name
    生成空引用
  • System.Security.Principal.WindowsIdentity.GetCurrent().Name
    的工作原理与
    Environment.Username
你对如何使用它有什么想法吗?谢谢

更新

根据环境,如果我获得登录id,我可以获得员工id、电子邮件等员工信息。。。从Employee表中。例如:我有一个类(在控制器之外)从Employee表中获取员工ID,以便像这样访问

string EmployeeID=new EmployeeService().EmployeeID()


根据反映的代码,HttpContext.Current.User是在windows authentication OnAuthenticate事件期间设置的

// System.Web.Security.WindowsAuthenticationModule
private void OnAuthenticate(WindowsAuthenticationEventArgs e)
{
    if (this._eventHandler != null)
    {
        this._eventHandler(this, e);
    }
    if (e.Context.User == null)
    {
        if (e.User != null)
        {
            e.Context.User = e.User;
            return;
        }
        if (e.Identity == WindowsAuthenticationModule.AnonymousIdentity)
        {
            e.Context.SetPrincipalNoDemand(WindowsAuthenticationModule.AnonymousPrincipal, false);
            return;
        }
        e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false);
    }
}
可能需要检查生产服务器上是否启用了windows身份验证,是否禁用了匿名身份验证


你能大致了解一下你想做什么吗?假设您正在尝试获取当前登录用户的用户名,那么您何时尝试使用它?也就是说,你在哪里使用这个“控制器外的类”?@RowanFreeman我刚刚更新了这个问题,请问什么时候调用这个类?是在调用操作之前、期间还是之后?是否为Windows身份验证正确设置了生产服务器?是否禁用匿名身份验证?
// System.Web.Security.WindowsAuthenticationModule
private void OnAuthenticate(WindowsAuthenticationEventArgs e)
{
    if (this._eventHandler != null)
    {
        this._eventHandler(this, e);
    }
    if (e.Context.User == null)
    {
        if (e.User != null)
        {
            e.Context.User = e.User;
            return;
        }
        if (e.Identity == WindowsAuthenticationModule.AnonymousIdentity)
        {
            e.Context.SetPrincipalNoDemand(WindowsAuthenticationModule.AnonymousPrincipal, false);
            return;
        }
        e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false);
    }
}