Propagating QueryString parameter in RedirectToAction calls

Arnab Chakraborty picture Arnab Chakraborty · Mar 27, 2012 · Viewed 11.8k times · Source

I want to make sure that a particular parameter in the QueryString, in my case the request_id is propagated to the redirected action.

Say for example, I have an Action First,

[HttpPost]
public ActionResult First() 
{
    ////////////////////
    // Lots of code ...
    ////////////////////

    return RedirectToAction("Second");
}

Now say, the First postback had a parameter in the QueryString, which I would like to pass to the Second action. One way to do it would be to pass the value in the RedirectToAction call itself,

string requestId = Request.QueryString[REQUEST_ID_KEY];
return RedirectToAction("Second", new { REQUEST_ID_KEY = requestId });

But I have to do this in a series of Actions and I am unwilling to incorporate request id propagation logic inside the action. It would be better if I could incorporate this inside an ActionFilter, but I cant figure out how to add parameters to the QueryString from an ActionFilter. Any ideas?

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 27, 2012
public class PreserveQueryStringAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var redirectResult = filterContext.Result as RedirectToRouteResult;
        if (redirectResult == null)
        {
            return;
        }

        var query = filterContext.HttpContext.Request.QueryString;
        // Remark: here you could decide if you want to propagate all
        // query string values or a particular one. In my example I am
        // propagating all query string values that are not already part of
        // the route values
        foreach (string key in query.Keys)
        {
            if (!redirectResult.RouteValues.ContainsKey(key))
            {
                redirectResult.RouteValues.Add(key, query[key]);
            }
        }
    }
}

and then:

[HttpPost]
[PreserveQueryString]
public ActionResult First() 
{
    ////////////////////
    // Lots of code ...
    ////////////////////

    return RedirectToAction("Second");
}