User.Identity.IsAuthenticated vs WebSecurity.IsAuthenticated

做~自己de王妃 提交于 2020-01-23 05:32:27

问题


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 or User.Identity has different functionality ?


回答1:


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.



来源:https://stackoverflow.com/questions/15853237/user-identity-isauthenticated-vs-websecurity-isauthenticated

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