2016-05-18 25 views
1

在我的ASP.NET MVC應用程序中,我大量使用了User.Identity.GetUserId()。不過,我不知道這是否有嚴重的表現處罰。User.Identity.GetUserId()的負擔是什麼?

另外,我相信我能做到這一點:在一個視圖中,我可以在第一頁加載當前用戶的ID分配給隱藏字段。然後,在進行AJAX調用時,我可以將隱藏的字段值傳遞給控制器​​的操作。這樣,我不需要使用User.Identity.GetUserId()方法來檢索當前用戶的用戶標識。

我不知道是否有人對此有什麼想法?

回答

2

看看源爲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; 
    } 
} 

您也可以創建一個服務來封裝該信息。