2013-04-06 18 views

回答

7

據我所知WebSecurity只是一個包裝。

這是正確的,兩者都是相同的。讓我們來看看WebSecurity.IsAuthenticated屬性是如何實現的:

public static bool IsAuthenticated 
{ 
    get 
    { 
     return Request.IsAuthenticated; 
    } 
} 

,現在讓我們來看看如何實現的WebSecurity.Request靜態屬性:

internal static HttpRequestBase Request 
{ 
    get 
    { 
     return Context.Request; 
    } 
} 

最後,讓我們來看看如何在WebSecurity.Context靜態屬性實現:

internal static HttpContextBase Context 
{ 
    get 
    { 
     return new HttpContextWrapper(HttpContext.Current); 
    } 
} 

因此,大家可以看到:

WebSecurity.IsAuthenticated 

是一樣的:

new HttpContextWrapper(HttpContext.Current).Request.IsAuthenticated 

這又是一樣Context.User.Identity.IsAuthenticated有細微的差別,有null檢查,如果例如Identity屬性爲null的屬性將返回false。

我應該使用它還是User.Identity具有不同的功能?

即使兩者完全等同我會用User.Identity這是官方的ASP.NET實現,因爲如果你決定更換別的東西簡單的成員資格提供你會少得多的東西來替代你的明天碼。

+0

所以遵循你的建議,爲了獲得UserId,我不會使用WebSecurity.CurrentUserId,而是使用Membership.GetUser()。ProviderUserKey? – 2013-04-06 16:37:31

+2

是的,兩者也是一樣的。你可以使用你喜歡的結果。 – 2013-04-06 16:38:29

相關問題