如何强制只匿名访问控制器操作?

Tar*_*tar 5 c# authentication asp.net-mvc asp.net-mvc-5

我可以使用该[AllowAnonymous]属性来允许用户访问控制器操作,但是是否有一个属性只允许匿名用户执行操作?例如[AllowAnonymousOnly]

And*_*ena 8

不,它不存在.

但是,您可以通过创建继承自AuthorizeAttribute的属性来创建它.

这是一个例子.

你的看起来像:

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
    }
}
Run Code Online (Sandbox Code Playgroud)