LogonUserIdentity.Name vs. User.Identity.Name

2019-05-05 11:36发布

问题:

I have an ASP.NET Web Forms Application project that is running upon the 4.0 framework. I'm very familiar with Web Applications, but not so much with Web Forms Applications. I ran into a notable difference between the two of them today, and I'm confused at why this difference even exists.

Typically, in a Web Application, if I want to determine who the current user of the page is then I just retrieve their domain log-in from User.Identity.Name. So, I was quite perplexed when I hit F5 to run my solution (my Web Forms Application!) in my debug environment and found that the User.Identity.Name was empty. So I then googled "User.Identity.Name is empty" and ran into a wall of links that mostly all dealt with people having this problem when they hadn't disabled Anonymous Authentication in IIS. Of course, that's not my problem (I think) as I'm just debugging from Visual Studio 2012 here.

However, I continued to dig and eventually found some obscure property on the HttpContext that is not empty and returns the user's domain log-in. The property is HttpContext.Current.Request.LogonUserIdentity.Name. Which leads me to my question...

Question: In my Web Forms Application, why is User.Identity.Name empty but HttpContext.Current.Request.LogonUserIdentity.Name is not?

Thanks in advance for the help!

EDIT: Forgot to state what I have in my web.config (because I'm sure it'll be asked for if I don't!).

<system.web>
  <customErrors mode="Off" />
  <compilation debug="true" targetFramework="4.0" />
  <authentication mode="Windows"/>
</system.web>
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="X-UA-Compatible" value="IE=10,chrome=1; IE=9,chrome=1; IE=8,chrome=1; IE=edge,chrome=1" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true" />
    <defaultDocument>
      <files>
        <add value="Home.aspx" />
      </files>
    </defaultDocument>
  </system.webServer>

That's pretty much all I have in my web.config besides tags for the EntityFramework.

回答1:

I found the answer on my own. The applicationhost.config for IIS Express was set to not allow windows authentication. I simply set enabled="true" and then User.Identity was no longer empty.

<windowsAuthentication enabled="true">
  <providers>
    <add value="Negotiate" />
    <add value="NTLM" />
  </providers>
</windowsAuthentication>

EDIT:
1) My apologies for the lack of information. I actually had the XML tags that I modified in my original answer, but I apparently forgot to mark them as being code by clicking on the Code Sample button, and so the XML tags were never displayed! They should be visible now.

2) The location of the applicationhost.config that I modified is down a few folders under My Documents. The exact location is: C:\Users[your user]\My Documents\IISExpress\config