FormsAuthentication.RedirectFromLoginPage()如何工作?

rip*_*234 7 asp.net-mvc redirect

它不会返回视图.实际上,在调用此函数后,Action仍然需要返回一个视图......那么发生了什么?

pat*_*dge 11

如果要使用FormsAuthentication系统,则需要切换到此行(隐式使用returnUrl参数).

return Redirect(FormsAuthentication.GetRedirectUrl(model.UserName, true));
Run Code Online (Sandbox Code Playgroud)

您将获得本FormsAuthentication.RedirectFromLoginPage已使用的URL ,但您将使用相应的操作方法明确地保释RedirectResult.

注意

如果你走这条路线,你将需要defaultUrl在表单auth web.config行中放置一个参数,以防有人直接进入你的登录页面(或者他们传入的表格redirectUrl没有通过FormsAuthentication的安全限制).如果不覆盖默认值,则会将错误的URL重定向到~/default.aspx.在大多数MVC应用程序中,这可能是404.

<forms loginUrl="~/Account/LogOn" defaultUrl="~/" timeout="2880">
Run Code Online (Sandbox Code Playgroud)

替代

如果您启动一个新的MVC 3示例"Internet应用程序",您将找到一个LogOn处理returnUrl类似于FormsAuthentication.RedirectFromLoginPage内部操作的操作方法.

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
    return Redirect(returnUrl);
}
else {
    return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)