【发布时间】:2018-04-05 17:03:04
【问题描述】:
场景如下:
- 从头开始一个 MVC 项目
- 用 [Authorize] 属性装饰的测试控制器
- 用户登录并定向到主页
- 用户点击一个链接会重定向到
TestController的Index方法 - 用户等待 60 秒以使表单身份验证超时
- 用户单击一个链接,该链接调用驻留在
TestController上的 ActionMethod - MVC 框架将用户重定向到登录页面并将 ActionMethod 名称附加到 URL,而不是附加
Index操作方法
TestController:
[Authorize]
public class TestController : Controller
{
// GET: Test
public ViewResult Index()
{
return View();
}
[ValidateInput(false)]
public ActionResult ActionTest()
{
return new EmptyResult();
}
}
HomeController:
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
AccountController:
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);
}
}
Login.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>
网络配置
<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 项目时,所有路由都是默认提供的
【问题讨论】:
-
分享您的路线和查看页面。还要在操作(或日志)中放置一个断点,以查看调用了哪个操作以及如果多个操作以什么顺序调用
-
@YishaiGalatzer,在表单身份验证超时后,我尝试再次登录,只命中了 SomePagePartialView 操作。
-
@YishaiGalatzer,该视图几乎只包含以下相关行:@Html.Action("SomePagePartialView")
-
URL 通常由路由生成。您尚未在问题中发布一条路线。
-
要么你的路由表有问题(我怀疑,但你应该检查一下),或者你的登录将你发送到部分视图而不是视图(调试它)。最后,您的主视图通过 Action("SomePagePartialView") 将您发送到局部视图,为了 100% 确定,现在让该视图返回其他内容(与 PartialViewPage 相同)
标签: asp.net-mvc security authentication asp.net-mvc-routing forms-authentication