How to force only anonymous access to controller action?

喜夏-厌秋 提交于 2019-12-05 10:41:54
André Pena

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!