Reputation: 3280
I am relatively new to ASP.NET MVC and I am encountering the following piece of code very often:
[Authorize]
public ActionResult Index()
{
if (Request.IsAuthenticated)
// ...
}
Is the if-statement really necessary? Can somebody please explain the differences between the two?
Upvotes: 2
Views: 1316
Reputation: 21881
The [Authorize]
attribute means that a user has to be logged in to call the controller endpoint.
Request.IsAuthenticated
is useful for condtionally running code for authenticated users e.g.
public ActionResult Index()
{
somecodethatrunsforeverybody();
if (Request.IsAuthenticated)
{
codethatrunsforauthenticatedusers();
}
}
So there is no point in decorating an action with [Authorize]
then wrapping the entire contents if an if (Request.IsAuthenticated)
. However it does have a use as per my example.
Upvotes: 1
Reputation: 141678
The if
check should not be needed. The [Authorize]
attribute does that, in fact it does more by checking role membership as well. Check out the implementation of AuthorizeAttribute
on GitHub to see how it works under the covers.
Upvotes: 6
Reputation: 191037
Authorize
can check role membership. The if
is redundant in this case as well.
That isn't a common pattern for ASP.NET MVC, you should ask who wrote the code.
This will just make testing a bit harder.
Upvotes: 3