Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in helper to parse User.Identity.Name into Domain\Username

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?

I understand that it's very easy to call String.Split("\") but just interesting

like image 804
abatishchev Avatar asked Dec 08 '08 13:12

abatishchev


2 Answers

System.Environment.UserDomainName gives you the domain name only

Similarly, System.Environment.UserName gives you the user name only

like image 31
StarCub Avatar answered Sep 24 '22 01:09

StarCub


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;     } } 

Usage:

IIdentity id = HttpContext.Current.User.Identity; id.GetLogin(); id.GetDomain(); 

This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.

like image 97
Aen Sidhe Avatar answered Sep 22 '22 01:09

Aen Sidhe