User.Identity.IsAuthenticated vs WebSecurity.IsAuthenticated

末鹿安然 提交于 2019-12-05 02:37:21

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 the Identity 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!