以下是场景的进展:
- 从头开始MVC项目
- 用[授权]属性修饰的测试控制器
- 用户登录并定向到主页
- 用户单击重定向到
TestController
的Index
方法的链接 - 用户等待60秒表单身份验证超时
- 用户单击一个链接,该链接调用驻留在
TestController
上的ActionMethod - MVC框架将用户重定向到登录页面,并将ActionMethod名称附加到URL,而不是附加
Index
Action Method
测试控制器:
[Authorize]
public class TestController : Controller
{
// GET: Test
public ViewResult Index()
{
return View();
}
[ValidateInput(false)]
public ActionResult ActionTest()
{
return new EmptyResult();
}
}
家庭控制器:
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
会计主管:
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
try
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
return RedirectToAction(controllerName: "Home", actionName: "Index");
}
catch
{
return View(model);
}
}
return View(model);
}
}
登录.chtml
@model TestLoginProject.Models.LoginViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
.....................
</head>
<body>
<div class="container">
@using (@Html.BeginForm("Login", "Account", new { returnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post, new { @class = "form-signin" }))
{
@Html.AntiForgeryToken()
....................
....................
}
</div>
</body>
</html>
Web配置
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="1" />
</authentication>
返回url的期望值是:
http://localhost:2441/Account/Login?ReturnUrl=%2fTest%2fIndex
相反,当前值为:
http://localhost:2441/Account/Login?ReturnUrl=%2fTest%2fActionTest
注释:
- 当用户在超时后单击链接时,在重定向到登录页面之前不会点击任何测试操作
- 所有路由都是在VS2017中从头开始Empty MVC项目时提供的默认路由
这是您提到的正常行为!
MVC框架将用户重定向到登录页面并附加ActionMethod名称到URL,而不是附加
Index
Action Method
非常感谢MVC安全管道。当您使用表单身份验证并且用户未经身份验证或授权时,ASP。NET安全管道重定向到登录页面,并将returnUrl
作为参数传递,该参数等于重定向到登录页的页面(这是需要授权的控制器操作,您可以通过单击链接调用该操作)。
因此,在这里,您不能期望索引(当前加载的页面没有有效和持久的身份验证),随后ActionMethod
调用安全管道,returnurl
被及时枚举。
请注意,这是因为控制器和视图之间的通信已同步。