简体   繁体   中英

Get the logged username to ASP.net application

I have this application I need to get the name of the windows logged user. I hosted this on a server. When I am tested locally this works perfectly but when I hosted on the server the program returns the server name, not the logged user username. My code is mentioned below

Index.cshtml

<h1>Hello @ViewBag.UserName</h1>

Controller

public ActionResult Index()
{
    string name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    string x = "";
    x = name.Split('\\')[1];
    ViewBag.UserName = x;
    return View();
}

Web.config

<system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
      <authentication mode="Windows"/>
  </system.web>

Any help is appreciated. Thank you.

Since you're using MVC in.Net framework, you can get the user's name/identity using:

string name = User.Identity.Name;

The reason it's returning the server is that WindowsIdentity.GetCurrent() returns the identity under which the thread is running, while User.Identity returns the identity which was passed to IIS.

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