在ASP中添加参数到当前URL的最佳方法。净MVC3

时间:2021-11-05 08:29:06

I ask a similar question here, I need to keep current URL and add new parameter to it, the only answer (yet) is :

我在这里问了一个类似的问题,我需要保持当前的URL并向它添加新的参数,唯一的答案是:

RouteValueDictionary rt = new RouteValueDictionary();
foreach(string item in Request.QueryString.AllKeys)
  rt.Add(item,    Request.QueryString.GetValues(item).FirstOrDefault());

rt.Add("RC", RowCount);
return RedirectToAction("Index", rt);

So is there any other way to avoid of repetition over Request.QueryString and just get current url and add new parameter?

还有其他方法可以避免重复请求吗?获取当前url并添加新参数?

1 个解决方案

#1


2  

you don't need to iterate the collection... you could simply append your parameters to the request's RawUrl:

您不需要迭代集合……只需将参数附加到请求的RawUrl:

    public ActionResult TestCurrentUrl(string foo)
    {
        var request = ControllerContext.HttpContext.Request;

        if (foo != "bar")
        {
            var url = request.RawUrl;

            if (request.QueryString.Count == 0)
            {
                url += "?foo=bar";
            }
            else
            {
                url += "&foo=bar";
            }

            return Redirect(url);
        }

        return Content(String.Format("Foo: {0}", foo));
    }

#1


2  

you don't need to iterate the collection... you could simply append your parameters to the request's RawUrl:

您不需要迭代集合……只需将参数附加到请求的RawUrl:

    public ActionResult TestCurrentUrl(string foo)
    {
        var request = ControllerContext.HttpContext.Request;

        if (foo != "bar")
        {
            var url = request.RawUrl;

            if (request.QueryString.Count == 0)
            {
                url += "?foo=bar";
            }
            else
            {
                url += "&foo=bar";
            }

            return Redirect(url);
        }

        return Content(String.Format("Foo: {0}", foo));
    }