How to change the greeting message on ASP.Net from

2019-09-17 23:29发布

问题:

How can I change the below mentioned code to show: Hello "First Name" instead of Hello "UserName".

I have already created some custom fields inside my Identity user table such as "FirstName","MiddleName","LastName".

Below mentioned code is inside Site.Master.

<li>
  <a runat="server" href="~/Account/Manage" title="Manage your account">
     Hello, <%: Context.User.Identity.GetUserName()  %> !
  </a>
</li>

I appreciate your efforts in reaching a solution for my problem.

回答1:

First Add Microsoft.AspNet.Identity.Owin namespace in web.config

<configuration>
   <namespaces>
       <!-- other namespaces -->
       <add namespace="Microsoft.AspNet.Identity.Owin"/>
  </namespaces>
</configuration>

then replace your code with:

<li>
    <a runat="server" href="~/Account/Manage" title="Manage your account"> Hello,
        <%: HttpContext.Current.GetOwinContext()
            .GetUserManager<YourNamespace.ApplicationUserManager>()
            .FindById(Context.User.Identity.GetUserId()).FirstName %>!
   </a>
</li>


回答2:

You will have to typecast the identity to the custom identity you made.. So you can use the field you used there. The code would look like this:

<li>
  <a runat="server" href="~/Account/Manage" title="Manage your account">
     Hello, <%: ((YourIdentity)Context.User.Identity).FirstName  %> !
  </a>
</li>


回答3:

Try using

HttpContext.Current.User.Identity.Name

It should work
Or you should try

User.Identity.Name