FormsAuthentication.RedirectToLoginPage() 与 RedirectToAction("Login", "Account")

FormsAuthentication.RedirectToLoginPage() vs RedirectToAction("Login", "Account")

我在我的网站上使用表单身份验证。我在一些示例代码中看到可以调用 .SignOut() 然后使用

FormsAuthentication.RedirectToLoginPage()

将用户发送到登录页面。

如果有的话,这比调用有什么优势

RedirectToAction("Login", "Account");

在 MVC 网站中?从 MSDN 看来,前者不会调用 HttpResponse.End() 这意味着后面的代码将执行...我不确定何时需要使用此功能。

FormsAuthentication.RedirectToLoginPage() 确实有一些优势,它会尝试将 ?ReturnUrl={url} 附加到登录页面 URL,稍后可以用于 return 用户到页面他们在登录重定向发生时请求。使用此方法使用 Response.Redirect(),这与 MVC 思想背道而驰。你会因为 controller/filters 开火而失去像 OnActionExecuting 这样的事件。 source code of RedirectToLoginPage

RedirectToAction("Login", "Account"); 没有开箱即用的 ReturnUrl 功能,但它确实将所有内容保留在 MVC 生态系统中,因此事件会触发。如果将某人注销并重定向回登录页面,我可能会将其全部保留在 MVC 中并使用 RedirectToAction。或者,如果您始终想使用 web.config.

中的登录页面 URL,则可以使用 Redirect(FormsAuthentication.Url);

执行 SignOut(),然后 return 执行 HttpUnauthorizedResult,这样控制器将只使用它的常规登录重定向。

如果您要退出 OnActionExecuting 控制器事件,请按此方式进行...

protected override void OnActionExecuting(ActionExecutingContext filterContext) {
    if (//I need to log out...) {
        System.Web.Security.FormsAuthentication.SignOut();
        filterContext.Result=new System.Web.Mvc.HttpUnauthorizedResult();
        return;
    }

    base.OnActionExecuting(filterContext);
}