仅允许在ASP.Net MVC中使用匿名的属性

H. *_*lyn 7 authentication asp.net-mvc authorization unauthorized

我知道用户必须进行授权时才有一个属性.你也可以放在[AllowAnonymous]它上面.另见下面的代码:

[Authorize] // only when the user is authorize
public class AccountController : Controller
{
    [HttpGet]
    [AllowAnonymous] // also when the user in not authorize.
    public ActionResult Login(string returnUrl = "")
    { /* Some code */ }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    { /* Some code */ }
}
Run Code Online (Sandbox Code Playgroud)

但是还有一个仅允许匿名的属性.例如:登录页面仅在用户未授权时显示

edi*_*ode 11

我不认为现有的,但没有理由你不能自己推出.但是,我想指出,您需要额外努力将内容限制为经过身份验证的用户,这似乎很奇怪:

public class AnonymousOnly : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
             // Do what you want to do here, e.g. show a 404 or redirect
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用这个新属性装饰你的类/方法:

[AnonymousOnly]
public ActionResult Login(string returnUrl = "")
{
    // code
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,将内容限制为经过身份验证的用户是很奇怪的,但我不会认为经过身份验证的您可以进入登录和注册页面。当他通过身份验证后,您无法再次进入登录页面进行身份验证...... (3认同)
  • @Hein如果是这两种情况,我只是检查他们是否已经在方法和"RedirectToAction"中登录,而不是为一个方法创建一个新类.话虽这么说,所有这一切都取决于偏好所以接近它,但是你和你的团队更喜欢. (2认同)