如何获取没有域名的用户名

doe*_*man 42 asp.net

在aspx页面中,我获得了带有该功能的Windows用户名Request.LogonUserIdentity.Name.此函数返回"domain\user"格式的字符串.

是否有一些功能只能获取用户名,而不是诉诸IndexOfSubstring,像这样?

public static string StripDomain(string username)
{
    int pos = username.IndexOf('\\');
    return pos != -1 ? username.Substring(pos + 1) : username;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_* V. 56

如果您使用的是Windows身份验证.这可以通过调用System.Environment.UserName只能为您提供用户名来实现.如果您只想要域名,则可以使用System.Environment.UserDomainName

  • 我的应用程序以我的身份运行,这为我返回"iis pool".很确定这个问题表明aspx,我相信这会在winforms中起作用. (6认同)
  • 在已发布的ASP.NET应用程序中,此属性返回应用程序池帐户的名称(例如Default AppPool)。 (3认同)

Rus*_*Cam 37

我不相信.我之前使用这些方法获得了用户名 -

var user = System.Web.HttpContext.Current.User;   
var name = user.Identity.Name;

var slashIndex = name.IndexOf("\\");
return slashIndex > -1 
    ? name.Substring(slashIndex  + 1)
    : name.Substring(0, name.IndexOf("@"));
Run Code Online (Sandbox Code Playgroud)

要么

var name = Request.LogonUserIdentity.Name;

var slashIndex = name.IndexOf("\\");
return slashIndex > -1 
    ? name.Substring(slashIndex  + 1)
    : name.Substring(0, name.IndexOf("@"));
Run Code Online (Sandbox Code Playgroud)


Vit*_*kov 21

获取零件[1]并不是一种安全的方法.我更喜欢使用LINQ .Last():

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity == null)
    throw new InvalidOperationException("WindowsIdentity is null");
string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();
Run Code Online (Sandbox Code Playgroud)

  • @MattWilko:我知道这是一篇旧帖子,但仅供参考(以防其他人好奇)即使域不存在,这种方法也能奏效。即,“domain\userid”和“userid”都将作为“userid”返回,至少在我测试时是这样。 (3认同)

Mr.*_*aus 5

如果您使用的是.NET 3.5,则可以始终为WindowsIdentity类创建一个扩展方法,以便为您执行此操作.

public static string NameWithoutDomain( this WindowsIdentity identity )
{
    string[] parts = identity.Name.Split(new char[] { '\\' });

    //highly recommend checking parts array for validity here 
    //prior to dereferencing

    return parts[1];
}
Run Code Online (Sandbox Code Playgroud)

那样你在代码中的任何地方都要做的就是参考:

Request.LogonUserIdentity.NameWithoutDomain();