ASP.Net MVC 中仅允许匿名的属性
Attribute for only allow anonymous in ASP.Net MVC
我知道当用户必须被授权时有一个属性。您也可以在其上方放置 [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 */ }
}
但是 allow anonymous only 还有一个属性吗?例如:登录页面仅在用户 未授权?
时显示
我认为没有现成的,但您没有理由不能推出自己的。但是,我要指出的是,您付出额外的努力将内容限制为经过身份验证的用户似乎很奇怪:
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
}
}
}
然后用这个新属性装饰你的 class/method:
[AnonymousOnly]
public ActionResult Login(string returnUrl = "")
{
// code
}
我知道当用户必须被授权时有一个属性。您也可以在其上方放置 [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 */ }
}
但是 allow anonymous only 还有一个属性吗?例如:登录页面仅在用户 未授权?
时显示我认为没有现成的,但您没有理由不能推出自己的。但是,我要指出的是,您付出额外的努力将内容限制为经过身份验证的用户似乎很奇怪:
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
}
}
}
然后用这个新属性装饰你的 class/method:
[AnonymousOnly]
public ActionResult Login(string returnUrl = "")
{
// code
}