ASP.NET MVC-通过RedirectToAction传递当前的GET参数
我正在寻找一种在传递当前请求的GET参数的同时使用RedirectToAction的方法.
I'm looking for a way to use RedirectToAction while passing along the current request's GET parameters.
因此,在进行以下操作时: http://mydomain.com/MyController/MyRedirectAction?somevalue=1234
So upon going to: http://mydomain.com/MyController/MyRedirectAction?somevalue=1234
然后我想通过重定向来重定向并保留somevalue,而不必显式构建路由字典并显式设置somevalue
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");
}
然后,重定向的操作可以使用somevalue:
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);
}
}
然后:
public ActionResult MyRedirectAction()
{
return new MyRedirectResult("MyAction", "Home", null);
}