内置的辅助解析User.Identity.Name到域\用户名 [英] Built-in helper to parse User.Identity.Name into Domain\Username
问题描述
有没有内置的实用工具或助手来解析 HttpContext.Current.User.Identity.Name
,例如: 域\用户
来是否存在,并得到独立域名的用户?
Is there any built-in utility or helper to parse HttpContext.Current.User.Identity.Name
, e.g. domain\user
to get separately domain name if exists and user?
或者有没有其他的类来做到这一点?
Or is there any other class to do so?
据我所知,这是很容易调用 String.Split(\)
只是有趣
I understand that it's very easy to call String.Split("\")
but just interesting
推荐答案
这是更好的(更容易使用, NullReferenceExcpetion
的没有机会,符合MS编码准则有关平等对待空和空字符串的):
This is better (easier to use, no opportunity of NullReferenceExcpetion
and conforms MS coding guidelines about treating empty and null string equally):
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编译后的工作。
This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.
这篇关于内置的辅助解析User.Identity.Name到域\用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!