【问题标题】:How can I use User.Identity.Name to work in a class outside of a Controller?如何使用 User.Identity.Name 在 Controller 之外的类中工作?
【发布时间】: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


【解决方案1】:

根据反映的代码,HttpContext.Current.User是在windows认证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 身份验证并禁用了匿名身份验证。

http://technet.microsoft.com/en-us/library/cc754628(v=WS.10).aspx

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 2011-04-21
    • 2017-02-21
    • 1970-01-01
    • 2014-02-09
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多