Asp.net-Mvc
在 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 */ } }但是是否還有一個只允許匿名的屬性。例如:登錄頁面僅在使用者未授權時顯示?
我不認為有一個現有的,但沒有理由你不能自己推出。但是,我要指出,您會付出額外的努力將內容限制為經過身份驗證的使用者,這似乎很奇怪:
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 }