User.Identity.IsAuthenticated VS WebSecurity.IsAuthenticated [英] User.Identity.IsAuthenticated vs WebSecurity.IsAuthenticated
问题描述
在一个MVC4应用程序,在控制器的逻辑我要检查,如果用户登录。结果
我应该使用:
User.Identity.IsAuthenticated
或者
WebSecurity.IsAuthenticated
据我所知 WebSecurity
只是一个包装。我应该使用它或 User.Identity
有不同的功能?
据我所知WebSecurity只是一个包装。
块引用>这是正确的,两者是相同的。让我们来看看
WebSecurity.IsAuthenticated
属性是如何实现的:公共静态布尔IsAuthenticated
{
得到
{
返回Request.IsAuthenticated;
}
}现在让我们来看看如何在
WebSecurity.Request
静态属性实现:内部静态的Htt prequestBase请求
{
得到
{
返回Context.Request;
}
}终于让我们来看看
WebSecurity.Context
静态属性是如何实现的:内部静态HttpContextBase上下文
{
得到
{
返回新HttpContextWrapper(HttpContext.Current);
}
}因此,大家可以看到:
WebSecurity.IsAuthenticated
是相同的:
新HttpContextWrapper(HttpContext.Current).Request.IsAuthenticated
这又是一样的
Context.User.Identity.IsAuthenticated
有细微的差别,有null检查和属性将返回false,如果例如身份
属性为null。
我应该使用它,或者User.Identity有不同的功能?
块引用>即使两者完全等同我会使用
User.Identity
这是官方的ASP.NET实现,因为如果明天您决定更换用简单的成员资格提供别的东西,你将有更少的东西在你的code来代替。In an MVC4 app, in a controller logic I want to check if the user is logged in.
Should I use:User.Identity.IsAuthenticated
Or:
WebSecurity.IsAuthenticated
As far as I know
WebSecurity
is just a wrapper. Should I use it orUser.Identity
has different functionality ?解决方案As far as I know WebSecurity is just a wrapper.
That's correct, both are the same. Let's have a look at how the
WebSecurity.IsAuthenticated
property is implemented:public static bool IsAuthenticated { get { return Request.IsAuthenticated; } }
and now let's look at how the the
WebSecurity.Request
static property is implemented:internal static HttpRequestBase Request { get { return Context.Request; } }
and finally let's have a look at how the
WebSecurity.Context
static property is implemented:internal static HttpContextBase Context { get { return new HttpContextWrapper(HttpContext.Current); } }
So as you can see:
WebSecurity.IsAuthenticated
is the same as:
new HttpContextWrapper(HttpContext.Current).Request.IsAuthenticated
which in turn is the same as
Context.User.Identity.IsAuthenticated
with a slight difference that there are null checks and the property will return false if for example theIdentity
property is null.Should I use it or User.Identity has different functionality ?
Even if the two are strictly equivalent I would use the
User.Identity
which is the official ASP.NET implementation because if tomorrow you decide to replace the simple membership provider with something else you will have far less things to replace in your code.这篇关于User.Identity.IsAuthenticated VS WebSecurity.IsAuthenticated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!