2016-06-13 740 views
0

這可能是重複問題,但我沒有從其他帖子中找到任何解決方案。HttpContext.Current.User.Identity.Name每次都是空的

我正在使用Windows身份驗證,當我在本地系統上構建應用程序時,它的工作正常,但是當我在IIS上部署應用程序時,HttpContext.Current.User.Identity.Name返回null。我已禁用身份驗證設置以外的Windows身份驗證。

var strUserName = HttpContext.Current.User.Identity.Name == "" ? System.Security.Principal.WindowsIdentity.GetCurrent().Name : HttpContext.Current.User.Identity.Name; 

我得到strUserName爲空。

<authentication mode="Windows"> 
</authentication> 

<identity impersonate="true"/> 

我試圖劃分線和編寫代碼來檢查究竟是什麼returing ...

HttpContext.Current.User.Identity.Name is returning null 
System.Security.Principal.WindowsIdentity.GetCurrent().Name is returning NT AUTHORITY\IUSR when impersonate is true 
System.Security.Principal.WindowsIdentity.GetCurrent().Name is returning IIS APPPOOL\ApplicationPoolName when impersonate is false 

以下幾個環節我已經檢查

HttpContext.Current.User.Identity.Name is empty using IIS Express but not Visual Studio Development Server

User.Identity.Name with windows authentication

+1

我想向您推薦[編輯]您的問題,並添加您發現的其他類似問題,並儘量避免將您的問題標記爲重複。 – kayess

+0

我相信第二個''標籤會覆蓋上面例子中的第一個,所以'mode = Windows'不會被拾取。你可以嘗試合併兩個配置項目嗎? –

+0

您是指服務/ WCF? –

回答

0

在Visual Studio Solution Explorer中 - Cli ck在web應用程序項目上 - >在底部選擇屬性選項卡。請確保您有以下設置:

  1. 匿名驗證| 已禁用
  2. Windows身份驗證| 啓用

改變你的web.config這樣的:

<system.web> 
    <authentication mode="Windows"/> 
    <compilation debug="true" targetFramework="4.5"/> 
    <httpRuntime/> 
    <pages controlRenderingCompatibilityVersion="4.0"/> 
    </system.web> 
    <system.webServer> 
    <modules> 
     <remove name="FormsAuthentication"/> 
    </modules> 
    </system.webServer> 

現在嘗試訪問當前的Windows用戶是這樣的:

string user = System.Web.HttpContext.Current.User.Identity.Name; 
+0

設置與您的建議相同,當我清理瀏覽器歷史記錄並將匿名身份驗證重新設爲禁用時,它將開始顯示用戶名密碼窗口,但它不接受憑據,我可以使用相同的憑據獲取遠程。它不應該直接顯示任何彈出窗口,它必須檢查用戶並重定向到默認屏幕。 – Rocky

+0

你使用MVC嗎? –

+0

沒有它簡單的asp.net應用程序 – Rocky