Dot*_*row 28 asp.net-mvc asp.net-mvc-3
我的剃刀视图中有一个链接,如下所示:
<a href="Home/Login?ReturnUrl=Disputes/Index"> disputes</a>
Run Code Online (Sandbox Code Playgroud)
在我的登录操作方法中,我使用这个:
public ActionResult Login(string returnUrl) {
if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
{
ViewBag.ReturnURL = returnUrl;
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
在视图我使用这个:
@Html.Hidden("returnUrl",@Request.QueryString)
Run Code Online (Sandbox Code Playgroud)
然后在post action方法中:
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (membershipService.ValidateUser(model.UserName, model.Password, model.Type))
{
formsAuthenticationService.SignIn(model.UserName, model.RememberMe);
SetUserInfo(model.UserName);
string decodedUrl = "";
if (!string.IsNullOrEmpty(returnUrl))
decodedUrl = Server.UrlDecode(returnUrl);
if (Url.IsLocalUrl(decodedUrl))
return Redirect(decodedUrl);
else
return Redirect("Home", Index);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它重定向到:/Disputes/Index但它应该转到myApp/Disputes/Index带有查询字符串的url是这样的./myApp/Home/Login?ReturnUrl=/Disputes/Index
我该如何解决这个问题?
Oli*_*ver 44
我使用上述建议的组合并Request.UrlReferrer获取以前的位置:
public ActionResult LogOn(string returnUrl)
{
//So that the user can be referred back to where they were when they click logon
if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
{
ViewBag.ReturnURL = returnUrl;
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
这样我就不必把位置放在了ActionLink.
我使用ViewBag.ReturnURL.填充登录页面中的隐藏字段.然后在Login HTTPPost中,ActionResult我将用户重定向到隐藏字段中的位置(如果有的话):
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
//returnURL needs to be decoded
string decodedUrl = "";
if (!string.IsNullOrEmpty(returnUrl))
decodedUrl = Server.UrlDecode(returnUrl);
//Login logic...
if (Url.IsLocalUrl(decodedUrl))
{
return Redirect(decodedUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以让LogOn操作采用returnUrl参数,如果它不为空,则可以返回重定向到Home/Index Redirect(returnUrl);.在创建新项目时,请查看VS生成的默认AccountController.它正是如此.
小智 6
如果ReturnURL是null,请确保从视图中调用action方法,如下所示:
// FormMethod.post is optional
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
// login view html
}
Run Code Online (Sandbox Code Playgroud)
账户管理员:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86656 次 |
| 最近记录: |