ASP.NET MVC-通过RedirectToAction传递当前的GET参数 [英] ASP.NET MVC - Pass current GET params with RedirectToAction

查看:265
本文介绍了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);
}

这篇关于ASP.NET MVC-通过RedirectToAction传递当前的GET参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆