简体   繁体   中英

How to show a username seperated from domain name like domain\username: in ASP.net so it can be used as a value

I'm setting up an application where in the footer, a Site.Master file contains a text Label to show "Welcome, username". Although I applied the right code, i cannot seem to get out text for the username.

I'm pretty new at this so can't see what I am doing anymore. Thank you so much in advance.

In the Site.Master file:

<asp:Label ID="Label1" runat="server" ></asp:Label>

In the Site.Master.cs file:

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
if (windowsIdentity == null)
throw new InvalidOperationException("WindowsIdentity is null");
string nameWithoutDomain = windowsIdentity.Name.Split('\\').Last();

Label1.Text = String.Format("Welcome,{0}", nameWithoutDomain);


[SOLUTION]

 var windowsIdentity = HttpContext.Current.User.Identity;

            if (windowsIdentity == null)
                throw new InvalidOperationException("WindowsIdentity is null");
            string nameWithoutDomain = HttpContext.Current.User.Identity.Name.Split('\\').Last();

            Label1.Text = String.Format("Welcome,{0}", nameWithoutDomain);    

WindowsIdentity.GetCurrent() gets the identity that the web site is running with, which will usually be the application pool identity. This is not the current user that has logged into your web site (unless you are using impersonation).

Use HttpContext.Current.User.Identity instead, which will give you the identity used to authenticate the current HTTP request.

This assumes that you have Windows Authentication working properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM