简体   繁体   中英

Windows Authentication - Get windows username

I have an MVC4 application which uses Windows Authentication (WA), which is setup on Webconfig file as such:

  <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:

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. I have looked at SQL Profiler. It seems to be taking the username as the DefaultAppPool , which is not bringing back any results!

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:

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

.Code in page:

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

msdn

Try HttpContext.User.Identity.Name . You retrieve the user's currently logged-in name via the current HttpContext .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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