I have an ASP.NET MVC app that with a controller. All of the actions in this controller can be accessed by anonymous users. However, if the user is authenticated, I want to do something special in the action. Currently, I've noticed that no matter what, User.Identity.IsAuthenticated is always false in the context of this action. Here is my code:
public class MyController : Controller
{
public ActionResult GetProfile(string id)
{
if (User.Identity.IsAuthenticated) {
ViewBag.ShowAuthStuff = true;
} else {
ViewBag.ShowAuthStuff = false;
}
}
}
How do I make it such that both an authenticated and an unauthenticated user can access the same action, but do different things? I can't figure out why User.Identify.IsAuthenticated is always false. I checked my cookies. When I'm logged in, there is a cookie named:
.ASPXAUTH
However, when I visit the action, that cookie is no longer available.
Just use both
Authorize
andAllowAnonymous
filters:Though it doesn't make a whole lot of sense to have anonymous access to a "profile".
Also, typically, you don't want to mix authorized and unauthorized actions in the same controller. It's better to have actions that must or may require authorization in a controller together, and unauthorized actions in a separate controller. In that case, you specify the
Authorize
filter on the controller itself, and thenAllowAnonymous
on any individual actions that want to interact with authenticated users, but don't require it.For example in an "Accounts" controller: