由于某种原因,asp.net mvc中的ReturnUrl为null

时间:2012-02-27 09:58:58

标签: asp.net-mvc-3

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中的 为空。

为什么呢?我该如何解决?

3 个答案:

答案 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"]})

请参阅davewasthere's answer

答案 2 :(得分:0)

在LogOn视图中验证:

  • 网址包含“returnUrl”
  • 形式的returnUrl字段