User.Identity.GetUserId() 的负担是什么?

What is the burden of User.Identity.GetUserId()?

在我的 ASP.NET MVC 应用程序中,我大量使用 User.Identity.GetUserId()。但是,我想知道这是否会严重影响性能。

或者,我相信我可以这样做:在视图中,我可以在第一个页面加载时将当前用户的 ID 分配给隐藏字段。然后,在进行 AJAX 调用时,我可以将隐藏字段值传递给控制器​​的操作。这样,我就不需要使用 User.Identity.GetUserId() 方法来检索当前用户的用户 ID。

不知道有没有人对此有什么想法?

查看 GetUserId 扩展方法的来源:

/// <summary>
///     Return the user id using the UserIdClaimType
/// </summary>
/// <param name="identity"></param>
/// <returns></returns>
public static string GetUserId(this IIdentity identity)
{
    if (identity == null)
    {
        throw new ArgumentNullException("identity");
    }
    var ci = identity as ClaimsIdentity;
    if (ci != null)
    {
        return ci.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    return null;
}

/// <summary>
///     Return the claim value for the first claim with the specified type if it exists, null otherwise
/// </summary>
/// <param name="identity"></param>
/// <param name="claimType"></param>
/// <returns></returns>
public static string FindFirstValue(this ClaimsIdentity identity, string claimType)
{
    if (identity == null)
    {
        throw new ArgumentNullException("identity");
    }
    var claim = identity.FindFirst(claimType);
    return claim != null ? claim.Value : null;
}

每次您调用该扩展方法时,它都会搜索 ClaimTypes.NameIdentifier 声明的身份。

对性能的影响不是很大(IMO),但是隐藏地泄露用户信息(如果单击一下 view source 就可以看到它们,实际上并没有隐藏)不是一个好主意。

如果您担心多次调用它并且在整个请求中需要在多个位置使用它,那么您可以将它延迟加载到控制器或基本控制器中的 属性 后面。

private string userId
public string UserId {
    get {
        if(userid == null) {
            userid = User.Identity.GetUserId();
        }
        return userid;
    }
}

您还可以创建一个服务来封装该信息。