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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With