【问题标题】:Getting The Current User Name In ASP.NET Application在 ASP.NET 应用程序中获取当前用户名
【发布时间】:2012-07-19 19:31:19
【问题描述】:

我正在运行一个需要能够读取当前用户的登录 ID 的网页。这是我正在使用的代码:

string id = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

目前这会返回正确的登录名,但是当我在此方法中使用它时:

protected Boolean isPageOwner()
{
    string id = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    alert("User: " + id);
    if (id.Equals(pageOwnerID))
    {
        return true;
    }
    if (accessPermission.ContainsKey(id))
    {
        return true;
    }
    return false;
}

即使返回的 id 与 pageOwnerID 相同,该方法也会返回 false。我真的不确定我的哪一部分有问题。

附带说明一下,我的登录 ID 的格式为 string1/string2,但代码将其检索为 string1 + string2 而不带斜线。

感谢任何建议。

问候。

【问题讨论】:

  • idpageOwnerID 的确切字符串是什么。从您的描述中听起来可能是abc/123abc123,这是行不通的。
  • 当我在我的本地机器上开发这个页面时,我能够以“abc/123”的形式检测到我的登录ID,并带有斜杠。一旦我在服务器上部署了页面,登录 id 就被检索到了,没有斜线 - 所以 abc123.因此,我更改了 pageOwnerID 以删除斜线,但相等性测试神秘地失败了。
  • 为什么不同时记录/输出idpageOwnerID 以便进行比较。显然它们不一样。
  • 你确定不是反斜杠吗,\?
  • 不要使用WinIdentity,使用Request.User

标签: c# asp.net


【解决方案1】:

尝试使用它来检索用户名....

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
   string username = System.Web.HttpContext.Current.User.Identity.Name;
}

听起来好像没有使用 windows 身份验证 - 您需要禁用匿名访问并启用 windows 集成安全性。

将此添加到您的 web.config...

<system.web>
 <authentication mode="Windows"/>
  <authorization>
    <deny users="?"/> 
  </authorization>
</system.web>

【讨论】:

  • 这在正常情况下是可行的,但 IIS 配置可能会设置模拟,从而使 ASP.NET 误以为 System.Web.HttpContext.Current.User.Identity.Name(或 Request.User.Identity. Name) 不是实际登录的用户。
  • 如果IsAuthenticated为假,则为空。
  • 啊,对不起,我的意思是我在没有 if 子句的情况下尝试了 string id = System.Web.HttpContext.Current.User.Identity.Name;。另外,这在我的 web.config 文件中:&lt;authentication mode="Windows" /&gt;
  • 您需要配置 IIS 以启用集成安全并禁用匿名。
  • 谢谢。我明天第一件事就是扑向服务器管理员。
【解决方案2】:

如果您需要任何层(或解决方案中的项目)中当前登录用户的身份,请使用:

string userId = Thread.CurrentPrincipal.Identity.GetUserId();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2011-07-21
    • 1970-01-01
    相关资源
    最近更新 更多