User.Identity.IsAuthenticated vs WebSecurity.IsAut

2020-08-22 03:52发布

问题:

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.