簡體   English   中英

Windows身份驗證-獲取Windows用戶名

[英]Windows Authentication - Get windows username

我有一個使用Windows身份驗證(WA)的MVC4應用程序,該程序在Webconfig文件中設置為:

  <system.web>
    <authentication mode="Windows"/>
  </system.web>

我正在使用以下代碼行獲取UserName,而我又在顯示的LINQ查詢中使用了UserName:

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

var  loc  = (from l in data.Locations.OrderBy(l => l.LocationName)
                        join s in data.LocationSecurities.Where(s=> s.UserName.Contains(userName)) on l.LocationID equals s.LocationId
                        select new
                        {
                            LocationId = l.LocationID,
                            Name = l.LocationName
                        }
                        ).ToList().Distinct();

這在調試模式下有效,但是在將應用程序發布到本地主機或Web服務器時無效。 我看過SQL事件探查器。 它似乎將用戶名用作DefaultAppPool ,這沒有帶來任何結果!

這是探查器跟蹤:

exec sp_executesql N'SELECT 
[Extent1].[LocationID] AS [LocationID], 
[Extent1].[LocationName] AS [LocationName]
FROM  [admin].[Location] AS [Extent1]
INNER JOIN [admin].[LocationSecurity] AS [Extent2] ON [Extent1].[LocationID] = [Extent2].[LocationID]
WHERE [Extent2].[UserName] LIKE @p__linq__0 ESCAPE N''~''',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'%DefaultAppPool%'

知道為什么會這樣嗎?

提前致謝。

要從操作方法(通過Windows身份驗證)中獲取當前登錄的用戶,您必須查詢當前的HttpContext,例如:

HttpContext.User.Identity.Name

您的web.config中的代碼:

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

。頁面中的代碼:

Response.Write(Page.User.Identity.Name);

msdn

嘗試HttpContext.User.Identity.Name 您可以通過當前HttpContext檢索用戶當前登錄的名稱。

暫無
暫無

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

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