我知道用户必须授权时才有属性。您也可以在其上方放置[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 */ }
}
但仅允许匿名还有一个属性。例如:登录页面仅在用户未授权时显示?
答案 0 :(得分:9)
我认为现有的不存在,但没有理由你不能自己动手。但是,我想指出,您需要额外努力将内容限制为经过身份验证的用户,这似乎很奇怪:
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
}
}
}
然后用这个新属性装饰你的类/方法:
[AnonymousOnly]
public ActionResult Login(string returnUrl = "")
{
// code
}