IAuthorizationFilter是否与属性相结合是检查用户是否在控制器运行之前登录的首选方法?
由于我是MVC的新手,我一直在试图弄清楚如何处理WebForms中完成的情况。我昨天遇到的是检查用户是否能够查看页面,具体取决于是否登录。在参与我的项目并将其“转变”为MVC项目时,我对如何解决这种情况感到不满。
使用WebForms版本,我使用基页来检查用户是否已登录:
if (State.CurrentUser == null)
{
State.ReturnPage = SiteMethods.GetCurrentUrl();
Response.Redirect(DEFAULT_LOGIN_REDIRECT);
}
我找到的是:
[AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext context)
{
if (State.CurrentUser == null)
{
context.Result =
new RedirectToRouteResult
(
"Login",
new RouteValueDictionary
(
new
{
controller = "Login",
action = "Error",
redirect = SiteMethods.GetCurrentUrl()
}
)
);
}
}
}
然后我只是在任何给控制器方法上打了那个属性,生活很好。问题是,这是首选和/或最佳方式吗?
答案 0 :(得分:2)
不要重新发明轮子。 MVC框架已经包含AuthorizeAttribute,它处理一些细微之处,而不是你在这里粘贴的代码,比如缓存。只是使用它。但是,属性是要走的路。
答案 1 :(得分:1)
使用FilterAttributes保护Controller操作是一种很好的方法。