簡體   English   中英

獲取 ASP.net 應用程序記錄的用戶名

[英]Get the logged username to ASP.net application

我有這個應用程序,我需要獲取 windows 登錄用戶的名稱。 我將它托管在服務器上。 當我在本地進行測試時,這工作得很好,但是當我托管在服務器上時,程序返回服務器名稱,而不是登錄的用戶用戶名。 我的代碼在下面提到

索引.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>

任何幫助表示贊賞。 謝謝你。

由於您在.Net 框架中使用 MVC,因此您可以使用以下方法獲取用戶的名稱/身份:

string name = User.Identity.Name;

它返回服務器的原因是WindowsIdentity.GetCurrent()返回運行線程的標識,而User.Identity返回傳遞給 IIS 的標識。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM