为什么ReturnUrl返回null参数虽然它出现在地址栏中?

问题描述 投票:0回答:2

什么可能是returnUrl字符串返回空值的原因,虽然它打印在地址栏中。在他的形式中,我创建了隐藏的输入标记,以便捕获URL并将其传递给ActionResult参数:

    @using (Html.BeginForm("Login", "Account", FormMethod.Post, ))
        {
                 @Html.AntiForgeryToken()
                 <input type="hidden" value="@Url.RequestContext.HttpContext.Request.QueryString["ReturnUrl"]"/>
               <input type="submit" value="Enter" class="btn btn-primary"/>
        }

因此,在点击提交按钮后,我被重定向到帐户控制器/登录ActionResult,其中ReturnUrl参数为null

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model,string ReturnUrl)
        {

            if (ModelState.IsValid)
            {
               //some codes
                    if (String.IsNullOrWhiteSpace(ReturnUrl))
                    {
                        return RedirectToAction("HomeIndex", "Home");
                    }
                    else
                    {
                        return Redirect(ReturnUrl);
                    }
                }
                else
                {
                    ModelState.AddModelError("UserLoginError", "Username or password is incorrect");
                }
            }
            return View(model);
        }

我也尝试将qerystring作为参数添加到Beginform的括号中,如下所示:

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { ReturnUrl = Request.QueryString["ReturnUrl"] } )) 

也没用。

asp.net asp.net-mvc
2个回答
1
投票

问题是你使用隐藏字段存储重定向的返回URL,它将作为Request.Form集合的一部分而不是控制器的POST操作方法中的单个操作参数发送。为了确保在表单提交期间包含返回URL,我建议您首先在viewmodel中添加返回URL属性:

public class LoginModel
{
    // other existing properties

    public string ReturnUrl { get; set; }
}

然后在GET操作中设置值,该操作呈现登录表单:

[HttpGet]
public ActionResult Login(string returnUrl)
{
    var model = new LoginModel() { ReturnUrl = returnUrl };
    return View(model);
}

并且您可以在表单中提供隐藏字段以保存其值:

@* using input hidden tag *@
<input name="ReturnUrl" value="@Model.ReturnUrl" type="hidden" />

@* using HTML helper *@
@Html.HiddenFor(model => model.ReturnUrl)

最后,返回URL可以在LoginModel实例中传递,不需要提供额外的参数:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        //some codes
        if (String.IsNullOrWhiteSpace(model.ReturnUrl))
        {
            return RedirectToAction("HomeIndex", "Home");
        }
        else
        {
            return Redirect(model.ReturnUrl);
        }
    }
    else
    {
        ModelState.AddModelError("UserLoginError", "Username or password is incorrect");
    }
    return View(model);
}

1
投票

看起来你缺少nameinput标签

<input type="hidden" name="returnUrl" value="@Url.RequestContext.HttpContext.Request.QueryString["ReturnUrl"]"/>

name属性必须与action参数名称相同。

© www.soinside.com 2019 - 2024. All rights reserved.