ash*_*999 6 redirect asp.net-mvc-3
在AccountController
我的MVC3应用程序中,如果returnUrl
已设置(在我的情况下,我手动设置),它将调用Redirect(returnUrl)
.
假设我的返回URL是/Admin/HealthCheck
(它确实是).当我调试时,我http://localhost:3279/Admin/HealthCheck
从重定向调用中得到一个URL .
然后,我部署了我的应用程序http://localhost/Test
.在这种情况下,Redirect(returnUrl)
重定向到http://localhost/Admin/HealthCheck
而不是预期的http://localhost/Test/Admin/HealthCheck
.
这里发生了什么?我该如何解决这个问题(如果它是可修复的)?
以下是(标准)MVC3 AccountController的片段; 你可以看到我从查询字符串中获取返回URL的位置(例如http://localhost/Test/LogOn?ReturnUrl=/Admin/HealthCheck
,尽管是URL编码的).
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
returnUrl = Request.Params["ReturnUrl"];
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
Run Code Online (Sandbox Code Playgroud)
(就我而言,我手动设置)
您实际上尚未展示此手动设置是如何发生的,但如果您对 url 进行了硬编码,而/Admin/HealthCheck
不是使用 url 帮助器来生成此 url,则Url.Action("HealthCheck", "Admin")
不要指望奇迹会发生。
你的LogOn
很好。它执行它应该执行的操作 => 它重定向到作为参数传递的 url。您的问题在于您设置此网址的方式。
结论:在 ASP.NET MVC 应用程序中,处理 url 时始终使用 url 帮助器。永远不要对它们进行硬编码。