I'm looking for a way to use RedirectToAction while passing along the current request's GET parameters.
So upon going to: http://mydomain.com/MyController/MyRedirectAction?somevalue=1234
I would then want to redirect and persist somevalue with the a redirect without having to explicitly build a route dictionary and explicitly setting somevalue
public ActionResult MyRedirectAction()
{
if (SomeCondition)
RedirectToAction("MyAction", "Home");
}
The redirected action could then use somevalue if available:
public ActionResult MyAction()
{
string someValue = Request.QueryString["somevalue"];
}
Is there a clean way to do this?
A custom action result could do the job:
public class MyRedirectResult : ActionResult
{
private readonly string _actionName;
private readonly string _controllerName;
private readonly RouteValueDictionary _routeValues;
public MyRedirectResult(string actionName, string controllerName, RouteValueDictionary routeValues)
{
_actionName = actionName;
_controllerName = controllerName;
_routeValues = routeValues;
}
public override void ExecuteResult(ControllerContext context)
{
var requestUrl = context.HttpContext.Request.Url;
var url = UrlHelper.GenerateUrl(
"",
_actionName,
_controllerName,
requestUrl.Scheme,
requestUrl.Host,
null,
_routeValues,
RouteTable.Routes,
context.RequestContext,
false
);
var builder = new UriBuilder(url);
builder.Query = HttpUtility.ParseQueryString(requestUrl.Query).ToString();
context.HttpContext.Response.Redirect(builder.ToString(), false);
}
}
and then:
public ActionResult MyRedirectAction()
{
return new MyRedirectResult("MyAction", "Home", null);
}