在MVC4應用程序,在控制器的邏輯我要檢查,如果用戶登錄
我應該使用:User.Identity.IsAuthenticated VS WebSecurity.IsAuthenticated
User.Identity.IsAuthenticated
或者:
WebSecurity.IsAuthenticated
據我所知WebSecurity
只是一個包裝。我應該使用它還是User.Identity
有不同的功能?
在MVC4應用程序,在控制器的邏輯我要檢查,如果用戶登錄
我應該使用:User.Identity.IsAuthenticated VS WebSecurity.IsAuthenticated
User.Identity.IsAuthenticated
或者:
WebSecurity.IsAuthenticated
據我所知WebSecurity
只是一個包裝。我應該使用它還是User.Identity
有不同的功能?
據我所知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實現,因爲如果你決定更換別的東西簡單的成員資格提供你會少得多的東西來替代你的明天碼。
所以遵循你的建議,爲了獲得UserId,我不會使用WebSecurity.CurrentUserId,而是使用Membership.GetUser()。ProviderUserKey? – 2013-04-06 16:37:31
是的,兩者也是一樣的。你可以使用你喜歡的結果。 – 2013-04-06 16:38:29