本文介绍了User.Identity.IsAuthenticated VS WebSecurity.IsAuthenticated的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个MVC4应用程序,在控制器的逻辑我要检查,如果用户登录。结果
我应该使用:

  User.Identity.IsAuthenticated

或者

  WebSecurity.IsAuthenticated

据我所知 WebSecurity 只是一个包装。我应该使用它或 User.Identity 有不同的功能?


解决方案

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 the Identity property is null.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 02:42