问题描述
是否有任何内置实用程序或帮助程序来解析 HttpContext.Current.User.Identity.Name
,例如domainuser
分别获取域名(如果存在)和用户?
Is there any built-in utility or helper to parse HttpContext.Current.User.Identity.Name
, e.g. domainuser
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 解析为 DomainUsername 的内置助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!