ASP.NET MVC Authorization
▌Introduction
In this article, we will use Controller.OnAuthorization to catch
requests of allow-anonymous routes.
▌Environment
▋MVC 5.2.3
▌Implement
▋Target Action
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (User.Identity.GetUserId() != null)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
|
▋BaseController
public class BaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
string actionName =
filterContext.RouteData.Values["action"].ToString();
string controllerName =
filterContext.RouteData.Values["controller"].ToString();
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
LogUtility.Logger.Info($"Requsest on allow-anonymous uri: {controllerName}/{actionName}");
return;
}
else
{
LogUtility.Logger.Info($"Requsest on uri: {controllerName}/{actionName} (使用者 : { User.Identity.Name})");
}
}
}
|
▋Result
▌Reference
沒有留言:
張貼留言