Tarostar
Tarostar

Reputation: 1316

How to force only anonymous access to controller action?

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]

Upvotes: 7

Views: 4304

Answers (2)

kamo_7
kamo_7

Reputation: 46

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.

Upvotes: 1

Andre Pena
Andre Pena

Reputation: 59446

No. It doesn't exist.

However, you can create it by creating your own attribute inheriting from the AuthorizeAttribute.

Here's an example.

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
    }
}

Upvotes: 11

Related Questions