3

I need to use HttpContext.Current.User.Identity.Name, but it always comes back as null. I have Anonymous Authentication set to disabled and Windows Authentication set to Enabled in the project properties. I also have the below lines in my web.config.

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

<providers>
....
  <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>

Server settings

Every post I have looked at has suggested doing the steps I have already done, but I still have no luck.

sjohn285
  • 315
  • 1
  • 13
  • Hosted in IIS or checking in VS? – Hary Nov 16 '18 at 14:36
  • Possible duplicate of [HttpContext.Current.User.Identity.Name is Empty](https://stackoverflow.com/questions/1571036/httpcontext-current-user-identity-name-is-empty) – Hary Nov 16 '18 at 14:37
  • Just checking in VS on localhost – sjohn285 Nov 16 '18 at 14:38
  • 2
    Also make sure you aren't trying to access the HttpContext identity too early in the application pipeline, such as in the Application_Start method of the Global.asax, as the identity won't be available there. – Thomas Nov 16 '18 at 14:45
  • Thanks Thomas! You were correct, I was getting the null error as soon as I ran the application. I moved the code into where I needed to get the user and it's working correctly now. If you make an answer I will mark it. – sjohn285 Nov 16 '18 at 14:51
  • I don't understand why people mark my question as a duplicate and downvote it within 10 minutes of posting. The duplicate question's answer is explicitly stated to not work in my post. – sjohn285 Nov 16 '18 at 14:52
  • I think a useful addition to the question would have been to include the context of your calling code that was throwing the exception, so that the problem would have been immediately obvious. I just guessed problem from the symptom in this case. To learn more about duplicate guidelines and why its useful for members to link to potential duplicates, I found [this page](https://stackoverflow.com/help/duplicates) useful. – Thomas Nov 16 '18 at 15:03

1 Answers1

0

Check it out with this

string userName = System.Web.HttpContext.Current.User.Identity.Name

or

User.Identity.Name
rykamol
  • 742
  • 1
  • 6
  • 16