简体   繁体   中英

Get current logged in user from within a view

I've got a view.cshtml that has a @model ....SportTeam at the top. I just want to check the Id from the AspNetUser table of the currently logged in user.

Do I have to do that in the Controller and then pass it into the View? Or can I check directly in the View?

In the View I can type in User.Identity but then all that I get after Identity is "name" and I want the Id.

Yes, you can get the User in the view - you can run any code you want in the view, but you should not. The whole point of MVC is to keep the view as dumb as possible. So move as much logic as possible into the controller and transfer the information you need via a model class.

If you don't like MVC, have a look a Razor pages, which replace MVC with just a view.

The below method will give you a logged-In user Id as a string and then you can have a property in your model that assigns this string and then you can pass it to the view.

 public string GetLoggedInUserId()
 {
    ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>()
                 .FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
    return user.Id;
 }

You will have to import the following:

using Microsoft.AspNet.Identity.Owin;

using Microsoft.AspNet.Identity;

I agree with @Christian. Put it in the controller. But if you need to get the userid in an easy way you can add and extension method for IIdenty. Like so:

 public static class IdentityExtensions
{
    public static Guid GetUserId(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity) identity).FindFirst(x => x.Type.ToLowerInvariant().Contains("nameidentifier"));
        // Test for null to avoid issues during local testing
        return claim != null ? Guid.Parse(claim.Value) : throw new ArgumentNullException(nameof(claim));
    }
}

Above code worked for me.

Hope it helps!

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