在aspx页面中,我获得了带有该功能的Windows用户名Request.LogonUserIdentity.Name.此函数返回"domain\user"格式的字符串.
是否有一些功能只能获取用户名,而不是诉诸IndexOf和Substring,像这样?
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
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)
如果您使用的是.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();
| 归档时间: |
|
| 查看次数: |
60539 次 |
| 最近记录: |