[英]Built-in helper to parse User.Identity.Name into Domain\Username
是否有任何內置的實用程序或幫助程序來解析
HttpContext.Current.User.Identity.Name
,例如domain\\user\u003c/code>如果存在和用戶單獨獲取域名?
或者還有其他課程嗎?
我知道調用
String.Split("\\")
非常容易,但很有趣
這樣更好( 更容易使用,沒有NullReferenceExcpetion
機會,並且符合關於同等處理空字符串和空字符串的MS編碼指南 ):
public static class Extensions
{
public static string GetDomain(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop) : string.Empty;
}
public static string GetLogin(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
}
}
用法:
IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();
這需要C#3.0編譯器(或更新版本),並且在編譯后不需要3.0 .Net來工作。
System.Environment.UserDomainName
僅為您提供域名
同樣, System.Environment.UserName
僅為您提供用戶名
var components = User.Identity.Name.Split('\\');
var userName = components.Last()
var domainName = components.Reverse().Skip(1).FirstOrDefault()
你們也可以考慮解析像“user@company.com”或“user @ domain”這樣的字符串輸入。
這就是我目前正在做的事情:
如果string包含'\\',則將字符串拆分為'\\'並提取用戶名和域名
否則如果字符串包含'@',則將字符串拆分為'@'並提取用戶名和域名
否則將字符串視為沒有域的用戶名
在輸入字符串不是易於預測的格式(即“domain \\ user @ domain”)的情況下,我仍在尋找更好的解決方案。 我在想RegEx ......
更新:我的立場得到糾正。 我的答案有點外向,它指的是用戶輸入解析用戶名和域的一般情況,例如在用戶登錄/登錄提示中。 希望它仍然可以幫助某人。
我想也沒有,因為我前幾天問自己同樣的問題:D
你可以試試:
public static string GetDomain(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop + 1) : null;
}
public static string GetLogin(string s)
{
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;
}
雖然不是.NET內置的,但總是可以P / Invoke到CredUIParseUserName 。 這是一個如何在.NET中使用它的示例。
PS:它似乎沒有處理“點”,如“。\\ username”。
我不這么認為,因為System.Security.Principal.WindowsIdentity不包含這樣的成員。
似乎是一個由正則表達式解決的問題:
public static class UserExtensions
{
public static string GetDomain(this IIdentity identity)
{
Regex.Match(identity.Name, ".*\\\\").ToString()
}
public static string GetLogin(this IIdentity identity)
{
return Regex.Replace(identity.Name, ".*\\\\", "");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.