Remove the domain name from User.Identity.Name
Asked Answered
N

2

7

I have he following method inside my action method:-

repository.InsertOrUpdateRack(rj.Rack, User.Identity.Name, assetid);

But the user name generated from User.Identity.Name will prefix the username with the domain name as follow:-

DOMAINNAME\username

So is there a way to force the User.Identity.Name to retrieve the username only? Thanks.

Nik answered 28/10, 2013 at 16:36 Comment(0)
E
16

The domain forms part of the username so I don't think any of the methods/properties return what you need. Can you not just do:

var userName = User.Identity.Name.Split('\\')[1];

Not ideal but simple enough. If you want to keep it nicely hidden away you could create an extension method on IIdentity.

The VB equivalent is (where UserWindowsName could be a variable or control used to display the Windows User Name):

Dim userName As WindowsIdentity = HttpContext.Current.Request.LogonUserIdentity
UserWindowsName = userName.Name.Split("\"c)(1)
Edan answered 28/10, 2013 at 16:55 Comment(1)
might be safer to use: var userName = WindowsIdentity.GetCurrent().Name.Split('\\').Last(); in case there is no domain prefixGause
L
0

var name = Regex.Replace(HttpContext.User.Identity.Name, @"^.*\", "");

Lief answered 20/5, 2021 at 18:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.