I can use the [AllowAnonymous]
attribute to permit a user to access a controller action, but is there an attribute to permit only anonymous users to an action? e.g. [AllowAnonymousOnly]
Asked
Active
Viewed 3,906 times
7

abatishchev
- 98,240
- 88
- 296
- 433

Tarostar
- 1,196
- 1
- 15
- 27
-
Out of curiosity, why do you need such a method ? – now he who must not be named. Apr 08 '15 at 11:55
-
1I have a registration run where the user gets an account created and automatically logged in and additional steps simply update the account with additional data. I wanted to prevent the user from hitting back or otherwise manually navigating to the first create user step once logged in. Doing so would of course only result in the user creating a new account, but could be confusing so I thought this might be the best way to prevent it. – Tarostar Apr 08 '15 at 12:26
2 Answers
11
No. It doesn't exist.
However, you can create it by creating your own attribute inheriting from the AuthorizeAttribute.
Yours would look like:
public class AllowAnonymousOnlyAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// make sure the user is not authenticated. If it's not, return true. Otherwise, return false
}
}

Community
- 1
- 1

Andre Pena
- 56,650
- 48
- 196
- 243
1
You could check the authentication of the user. If the user is logged in, then redirect him away from the controller. This can be achieved as follows using MVC's role provider:
if (User.Identity.IsAuthenticated)
{
return RedirectToRoute("home");
}
If the user is not logged in, this will then allow the user to view the contents of the page.