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

How to force only anonymous access to controller action?

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

没有。它不存在。

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

Here's an example.

你的看起来像:

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

您可以检查用户的身份验证。如果用户已登录,则将他从控制器重定向。这可以使用 MVC 的角色提供者按如下方式实现:

        if(User.Identity.IsAuthenticated)
        {
            return RedirectToRoute("home");
        }   

如果用户没有登录,这将允许用户查看页面内容。