public ActionResult LogOn(string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction(string.Empty, "home");
}
else
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//http://localhost:666/en-us/account/logon?returnurl=%2fen-us%2fadminka
//..............
}
return View();
}
}
[HttpPost]
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (....)
{
//..............
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return Redirect(returnUrl);
return RedirectToAction(string.Empty, "home");
}
else
{
//..............
}
}
return View(model);
}
HttpPost LogOn
returnUrl
始终等于null,即使HttpGet LogOn
中的 为空。
为什么呢?我该如何解决?
答案 0 :(得分:11)
您需要使用表单帖子发布returnUrl。
可能最干净的解决方案是将returnUrl作为属性添加到LogOnViewModel:
public class LogOnViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ReturnUrl { get; set; }
}
你的get方法会设置该值:
[HttpGet]
public ActionResult LogOn(string returnUrl)
{
// code for already authenticated case left out for demo
var model = new LogOnViewModel { ReturnUrl = returnUrl };
return View(model);
}
}
在您的表单中,您会将该值保留为隐藏字段:
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ReturnUrl)
// rest of form code left out for demo purposes
}
您的帖子方法可以访问该值:
[HttpPost]
public ActionResult LogOn(LogOnViewModel model)
{
if (ModelState.IsValid)
{
if (....)
{ string returnUrl = model.ReturnUrl;
//..............
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return Redirect(returnUrl);
return RedirectToAction(string.Empty, "home");
}
else
{
//..............
}
}
return View(model);
}
答案 1 :(得分:2)
在登录视图中,将ReturnUrl
参数添加到表单操作中。例如:
BeginForm("LogOn", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"]})
答案 2 :(得分:0)
在LogOn视图中验证: