C# – Copying HTTP request parameters in call to RedirectToAction

I have been learning C# over the past year and today I encountered a situation with Controller.RedirectToAction() that I took awhile to find a solution to so I wanted to write down my solution.

In my case, I was in a method in a Controller (accessed from a HTTP GET) and needed to invoke RedirectToAction().  However, as part of the call to RedirectToAction() I needed to send along all the HTTP request parameters.

First of all, this is the method in the class FirstController that handled the initial GET request:

public ActionResult HandleRequest1() 
  // Create a dictionary containing the query string parameters
   var queryStringParams = this.Request.QueryString.AsRouteValueDictionary();
  // Pass the queryStringParams dictionary to RedirectToAction
   return this.RedirectToAction<SecondController>(x => x.HandleRequestTwo(), queryStringParams);

Second, this is the method in the class SecondController that was redirectedTo:

public ActionResult HandleRequestTwo() 
  string urlParamsStr = HttpContext.Request.Params.ToString();
  NameValueCollection queryParams = HttpUtility.ParseQueryString(urlParamsStr);
  string value1= queryParams["paramKey1"];
  return new View("SecondView");

In the end, it was creating a Dictionary that solved the problem.


About stevewall123

I am a Lead Software Engineer in Minneapolis working for Thomson Reuters. I am currently working on projects using Java, JavaScript, Spring, Elasticsearch, Hazelcast, Liquibase and Tomcat. Previously, I used C#, GWT, Grails, Groovy, JMS and JBoss Drools Guvnor. In the past I have worked on projects using J2EE, Swing, Webwork, Hibernate, Spring, Spring-WS, JMS, JUnit and Ant.
This entry was posted in C# and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s