【问题标题】:MVC redirect problemMVC 重定向问题
【发布时间】:2009-07-28 22:31:13
【问题描述】:

我正在为我的所有控制器实现一个继承类,如果用户未通过身份验证,它将重定向到登录页面。 RedirectToAction 行虽然没有重定向。可以帮忙改正吗?

public class SecureController : Controller
    {
        public SecureController()
        {
            if (User == null || !User.Identity.IsAuthenticated)
            {
                RedirectToAction("Logon", "Account");
            }
        }
    }

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我的建议是改用 ActionFilter。这会容易得多。你可以这样做:

    public class RequiresAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // You can do any custom authentication logic in here
    
            if (User == null || !User.Identity.IsAuthenticated)
            {
                // This assumes that Account is the controller, and Logon is the action method.
                // You might want to check your routes if this is still not working correctly
                RedirectToAction("Logon", "Account");
            }
        }
    }
    

    这将让您在控制器中的操作方法上添加一个属性,如下所示:

    [RequiresAuthentication]
    public ActionResult Index()
    {
        return View();
    }
    

    或者,正如其他人指出的那样,如果您不需要任何自定义身份验证逻辑,则可以使用 AuthorizeAttribute:

    [Authorize]
    public ActionResult Index()
    {
        return View();
    }
    

    【讨论】:

    • 我认为他需要进行自定义身份验证,因为他正朝着自己的方向发展。这是我使用的属性类型,我只是替换了我所有的自定义身份验证逻辑。
    • 关于过滤器的好建议。我正在实现自己的授权逻辑,过滤器会派上用场。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多