简体   繁体   English

从视图中获取当前登录的用户

[英]Get current logged in user from within a view

I've got a view.cshtml that has a @model ....SportTeam at the top. 我有一个view.cshtml,它的顶部有一个@model .... SportTeam。 I just want to check the Id from the AspNetUser table of the currently logged in user. 我只想从当前登录用户的AspNetUser表中检查ID。

Do I have to do that in the Controller and then pass it into the View? 我是否必须在Controller中执行此操作,然后将其传递给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. 在视图中,我可以键入User.Identity,但是在Identity之后,我得到的所有内容都是“名称”,并且我需要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. MVC的全部目的是保持视图尽可能的愚蠢。 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. 如果您不喜欢MVC,请看一下Razor页面,这些页面仅用视图代替了MVC。

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. 下面的方法将为您提供一个已登录用户ID作为字符串,然后您可以在模型中拥有分配该字符串的属性,然后可以将其传递给视图。

 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. 我同意@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. 但是,如果您需要以简单的方式获取用户ID,则可以为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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM