C# User.Identity.IsAuthenticated vs.WebSecurity.IsAuthenticated
在MVC4应用程序中,我想在控制器逻辑中检查用户是否登录。C# User.Identity.IsAuthenticated vs.WebSecurity.IsAuthenticated,c#,authentication,asp.net-mvc-4,forms-authentication,C#,Authentication,Asp.net Mvc 4,Forms Authentication,在MVC4应用程序中,我想在控制器逻辑中检查用户是否登录。 我应该使用: User.Identity.IsAuthenticated 或: 据我所知,WebSecurity只是一个包装器。我应该使用它还是User.Identity具有不同的功能 据我所知,网络安全只是一个包装 没错,两者都是一样的。让我们看看WebSecurity.IsAuthenticated属性是如何实现的: public static bool IsAuthenticated { get {
我应该使用:
User.Identity.IsAuthenticated
或:
据我所知,WebSecurity
只是一个包装器。我应该使用它还是User.Identity
具有不同的功能
据我所知,网络安全只是一个包装
没错,两者都是一样的。让我们看看WebSecurity.IsAuthenticated
属性是如何实现的:
public static bool IsAuthenticated
{
get
{
return Request.IsAuthenticated;
}
}
internal static HttpRequestBase Request
{
get
{
return Context.Request;
}
}
internal static HttpContextBase Context
{
get
{
return new HttpContextWrapper(HttpContext.Current);
}
}
现在让我们看看WebSecurity.Request
静态属性是如何实现的:
public static bool IsAuthenticated
{
get
{
return Request.IsAuthenticated;
}
}
internal static HttpRequestBase Request
{
get
{
return Context.Request;
}
}
internal static HttpContextBase Context
{
get
{
return new HttpContextWrapper(HttpContext.Current);
}
}
最后,让我们看看WebSecurity.Context
静态属性是如何实现的:
public static bool IsAuthenticated
{
get
{
return Request.IsAuthenticated;
}
}
internal static HttpRequestBase Request
{
get
{
return Context.Request;
}
}
internal static HttpContextBase Context
{
get
{
return new HttpContextWrapper(HttpContext.Current);
}
}
如你所见:
WebSecurity.IsAuthenticated
同:
new HttpContextWrapper(HttpContext.Current).Request.IsAuthenticated
这与Context.User.Identity.IsAuthenticated
相同,但有一点不同,即存在空检查,例如Identity
属性为空时,属性将返回false
我应该使用它还是使用User.Identity具有不同的功能
即使两者完全相同,我也会使用ASP.NET官方实现的
User.Identity
,因为如果明天你决定用其他东西替换简单的会员资格提供者,那么你的代码中要替换的东西就会少得多。所以按照你的建议,获取用户ID,我不会使用WebSecurity.CurrentUserId,而是使用Membership.GetUser().ProviderUserKey?是的,两者也是一样的。你可以用你喜欢的那种,效果也一样。