Query string is missing from return url

1k views Asked by At

So, I have an action which is allowed for authorized users only.

[HttpPost]
[Authorize]
public ActionResult DoSomething(string data)
{
    StoreData(data);
    return RedirectToAction("Index", "Home");
}

In the view, I call this action:

@using (Html.BeginForm("DoSomething", "Home"))
{
    @Html.Hidden("data", "12345")
    <input type="submit" value="DoIt" /> 
}

If the user is not authorized, he/she will be redirected to the login page, but the ReturnUrl doesn't contain the query string(in this case, the value of the "data")

http://localhost:62978/Account/Login?ReturnUrl=%2fHome%2fDoSomething

Why is that and could I fix it?

1

There are 1 answers

0
Adrian Toman On

When a HTML forms's method is POST the form data is sent in the HTTP request's body. However when a form's method is GET the form data is sent as a part of the URL in the HTTP request.

BeginForm will by default render a form with a method="Post". You either need to explictly set the form's method to FormMethod.Get. Example:

@using (Html.BeginForm("DoSomething", "Home", FormMethod.Get))

Alternatively, require user authorization prior to displaying the form. That is to say add the Authorize attribute to the action that is rendering the view. Example:

[Authorize]
public ActionResult DoSomething()
{
    View();
}