简体   繁体   中英

asp.NET - Get Username while on the Server

I have a small problem, I have an application which used to work perfectly locally. The authentication was being done from a system I built myself, it was basically using the username of the logged in user, but when deploying on the server I ran into a problem because it was using the servers username instead of the user which is trying to access it.

This was the code which was working, but now it's not on the server:

    public static string GetUser()
    {
        WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
        WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
        return curIdentity.Name;
    }

However I can see that this code:

     <LoggedInTemplate>
        <span class="alignLeft">
           <asp:LoginName ID="HeadLoginName" runat="server"/>
        </span>
        <span class="alignRight">
           <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/Logout.aspx"/>
        </span>
     </LoggedInTemplate>

, still used to good login of the user and not the server. I am now trying to get the value of that user, but I am having problems to do that.

All I need to do is to get that in a string.

loginName.Text = HeadLoginName.ToString().Substring(6);

This only returned: ".Web.UI.WebControls.LoginName". I need the substring to remove the domain name before the user.

use

User.Identity.Name

instead of HeadLoginName function.

loginName.Text = User.Identity.Name;

What code were you using to try to get the user´s name before? How are your users logging in?

HttpContext.Current.User.Identity.Name ?

I´m not sure if you could ever pull the user´s login name out of the LoginName web control (I suspect not), but I suggest finding a less roundabout way of doing it. The above code has always worked for me.

Menno

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