Search code examples
asp.netasp.net-mvcasp.net-mvc-3action-filterredirecttoaction

Propagating QueryString parameter in RedirectToAction calls


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?


Solution

  • 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");
    }