本文介绍了ASP.Net MVC:用于登录个IAuthorizationFilter /属性prefered安全检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是个IAuthorizationFilter加上一个属性preferred的方式来检查,如果用户登录在控制器上运行它当然过吗?

Is IAuthorizationFilter coupled with an attribute the preferred way to check if a user is logged in before a controller runs it's course?

由于我是新来的MVC我一直在试图找出如何处理的WebForms完成的情况。我跑进昨天一个检查,看看用户能够查看页面或不取决于是否登录与否。当拍摄我的一个项目,改造它变成一个MVC项目,我有点在如何解决这种情况的赔率。

Since I'm new to MVC I've been trying to figure out how to handle situations done in WebForms. The one I ran into yesterday is checking to see if the user is able to view a page or not depending on whether logged in or not. When taking a project of mine and "transforming" it into an MVC project, I was a little at odds on how to solve this situation.

随着的WebForms的版本,我用了一个基本页面,检查如果用户登录:

With the WebForms version, I used a base page to check if the user was logged in:

if (State.CurrentUser == null)
{
  State.ReturnPage = SiteMethods.GetCurrentUrl();
  Response.Redirect(DEFAULT_LOGIN_REDIRECT);
}

我确实发现是这样的:

What I did find is this:

[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()
                  }
                )
              ); 
        }
    }
}

然后我就打这个属性在任​​何给控制器的方法和生活是美好的。问题是,这个preferred和/或要做到这一点最好的方式?

Then I just slap that attribute on any give controller method and life is good. Question is, is this the preferred and/or best way to do this?

推荐答案

不要推倒重来。 MVC框架已经包含AuthorizeAttribute,它可以处理一些细微之处没有在code你已经粘贴在这里,比如缓存。只需使用。但是,是的,属性是要走的路。

Don't reinvent the wheel. The MVC framework already includes AuthorizeAttribute, which handles some subtleties not in the code you've pasted here, such as caching. Just use that. But yes, attributes are the way to go.

这篇关于ASP.Net MVC:用于登录个IAuthorizationFilter /属性prefered安全检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:20