3

我想檢查使用Windows身份驗證的用戶的登錄名。 我有這個作爲我的控制器的構造函數:MVC中的Windows身份驗證

public class HomeController : BaseController 
{ 
    public string UserIdentityName; 

    public HomeController() 
    { 
     UserIdentityName = System.Web.HttpContext.Current.User.Identity.Name;// HttpContext.Current.User.Identity.Name; 
    } 
} 

但UserIdentityName返回空字符串...

我也有這個在我的web.config:

<authentication mode="Windows" /> 

什麼想法?

回答

5

不要嘗試訪問控制器構造函數中的任何HttpContext相關的東西。您應該訪問它的最早階段是Initialize方法或在控制器操作中。

例如:

[Authorize] 
public ActionResult Index() 
{ 
    string user = User.Identity.Name; 
    ... 
} 

另外,還要確保你有你的Web服務器上啓用Windows身份驗證(NTLM)。

+0

我仍然得到空... –

+1

您可能尚未將您的Web服務器配置爲需要Windows身份驗證。 –

+0

Im使用Casini ... –

1

嘗試增加:

<authorization> 
    <deny users="?" /> 
</authorization> 

拒絕匿名用戶訪問。

11

在解決方案資源管理器窗格中選擇Web項目並按F4。 (不右鍵+屬性,那是不同的)

在屬性面板設置:
Windows身份驗證:啓用
匿名身份驗證:殘疾人

在web.config中:<authentication mode="Windows"></authentication>

要獲取用戶名:

HttpContext.Current.User.Identity.Name OR User.Identity.Name 

運行你的項目,快樂的日子!

+0

這似乎並沒有在VS 2010 :( – 2013-02-05 21:32:58

+0

雙重檢查。我犯了這個錯誤 - 有兩個設置頂部的匿名身份驗證和項目屬性底部的Windows身份驗證我創建了一個虛擬的Intranet MVC應用程序並閱讀要實現的readme.txt。 – Pete

2

Chaps,

如果您在IISExpress中運行。請確保以下設置如圖:

在web.config中

<authentication mode="Windows"/> 
<authorization> 
    <deny users="?"/> 
</authorization> 

在記事本中打開projectName.csproj並糾正follwing設置:

<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication> 
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication> 

<UseIIS>True</UseIIS> 
+0

以上回答編輯文件.csproj正在爲我工​​作。謝謝@Radim – banny