C# 在 ASP.NET 应用程序中获取当前用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11567965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:22:26  来源:igfitidea点击:

Getting The Current User Name In ASP.NET Application

c#asp.net

提问by Kevin

I am running a webpage that needs to be able to read the login id of the current user. Here is the code I am using:

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

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

Currently this returns the correct login but when I use it in this method:

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

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;
}

the method returns false even though the id returned is identical to pageOwnerID. I'm really not sure which part of this I am having a problem with.

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

On a side note, my login id is of the form string1/string2 but the code retrieves it as string1 + string2 without the slash.

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

Any advice is appreciated.

任何建议表示赞赏。

Regards.

问候。

采纳答案by SliverNinja - MSFT

Try using this to retrieve the username....

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

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

It sounds like windows authentication is not being used - you need to disable anonymous access and enable windows integrated security.

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

Add this to your web.config...

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

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

回答by Ehimah Obuse

If you need the current logged in user's identity from within any layer (or Project in your solution) then use:

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

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

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