MVC Core @User.Identity.Name in razor returns null

It runs just fine and returns the name on my local machine (windows authentication) by using @User.Identity.Name. However, if I move it from my local to dev server, it just returns the text without the name. Not sure why @User.Identity.Name doesn’t work when I push.

<div class="navbar-collapse">
   <p class="nav navbar-text navbar-right">    
      <script id="greetings">
         document.write('Hello, ');
      </script>
      @User.Identity.Name
  </p>
</div>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It runs just fine and returns the name in my local (windows authentication) by using @User.Identity.Name. However, if I move it from my local to dev server, it just returns the text without the name.

As we discussed in comments, if Anonymous Authentication is enabled, which will cause this issue.

Besides, we can check if the user is authenticated first, then display the name of current non-anonymous user in view page instead of accessing User.Identity.Name directly.

<div class="navbar-collapse">
    <p class="nav navbar-text navbar-right">
        <script id="greetings">
            document.write('Hello, ');
        </script>
        
        @if (User.Identity.IsAuthenticated)
        {
            <span>@User.Identity.Name</span>
        }
        else
        {
            <span>Anonymous user</span>
        }

    </p>
</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x