简体   繁体   English

Windows身份验证-获取Windows用户名

[英]Windows Authentication - Get windows username

I have an MVC4 application which uses Windows Authentication (WA), which is setup on Webconfig file as such: 我有一个使用Windows身份验证(WA)的MVC4应用程序,该程序在Webconfig文件中设置为:

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

I am using this line of code to get the UserName, which in turn I am using in the LINQ Query shown: 我正在使用以下代码行获取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();

This works in debug mode, however it doesn't when the Application is published to the localhost or the Webserver. 这在调试模式下有效,但是在将应用程序发布到本地主机或Web服务器时无效。 I have looked at SQL Profiler. 我看过SQL事件探查器。 It seems to be taking the username as the DefaultAppPool , which is not bringing back any results! 它似乎将用户名用作DefaultAppPool ,这没有带来任何结果!

This is the profiler trace: 这是探查器跟踪:

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%'

Any idea on why this is happening? 知道为什么会这样吗?

Thanks in advance. 提前致谢。

要从操作方法(通过Windows身份验证)中获取当前登录的用户,您必须查询当前的HttpContext,例如:

HttpContext.User.Identity.Name

Code in your web.config: 您的web.config中的代码:

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

.Code in page: 。页面中的代码:

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

msdn msdn

Try HttpContext.User.Identity.Name . 尝试HttpContext.User.Identity.Name You retrieve the user's currently logged-in name via the current HttpContext . 您可以通过当前HttpContext检索用户当前登录的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM