将键值对附加到查询字符串

时间:2015-01-23 07:53:48

标签: c# webforms query-string

我想通过格式化常规字符串然后将其附加到当前查询字符串,将多个查询字符串键值对添加到URL。因为,据我所知,没有办法改变实际的Request.QueryString。因此,我尝试将kvp:s附加到查询字符串,如下所示。我搜索过StackOverflow,但找不到符合我问题的答案。

protected void ServiceSelectionChanged(object sender, EventArgs e)
{
    var regNr = registrationNumber.Text;
    var selectedServiceType = SelectedServiceType.ToString("D");

    string url = string.Empty;
    BookingHelpers.FormatQueryStringUrl(this.Request, "serviceType", selectedServiceType, ref url);
    BookingHelpers.FormatQueryStringUrl(this.Request, "regNr", regNr, ref url);
    Server.Transfer(url, false);
}

public static void FormatQueryStringUrl(HttpRequest request, string key, string value, ref string url)
{
    if (string.IsNullOrEmpty(url))
    {
        url = request.Url.PathAndQuery; 
    }
    if (url.Contains("?"))
    {
        if (url.Contains("&" + key))
        {
            string currentValue = request.QueryString[key];
            url = url.Replace("&" + key + "=" + currentValue, "&" + key + "=" + value);
        }
        else
        {
            url = String.Format(request.Url.PathAndQuery + "&" + key + "={0}", value);
        }
    }
    else url = String.Format(request.Url.PathAndQuery + "?" + key + "={0}", value);
}

然而,每次都使用Request.QueryString,因此第一个kvp被覆盖。所以我的问题是:我如何才能使这个工作能够将两个键值对附加到查询字符串中?

1 个答案:

答案 0 :(得分:0)

我找到了有关堆栈溢出的答案,这对我有帮助:

How to build a query string for a URL in C#?

虽然,我还需要检查网址中是否已经有一个查询字符串,所以我将其修改为类似的内容。

public static string ToQueryString(string url, NameValueCollection nvc)
    {
        StringBuilder sb;

        if (url.Contains("?"))
            sb = new StringBuilder("&");
        else
            sb = new StringBuilder("?");

        bool first = true;

        foreach (string key in nvc.AllKeys)
        {
            foreach (string value in nvc.GetValues(key))
            {
                if (!first)
                {
                    sb.Append("&");
                }

                sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));

                first = false;
            }
        }

        return url + sb.ToString();
    }

而用法改为:

var queryParams = new NameValueCollection() 
{
    { "isaServiceType", selectedIsaServiceType },
    { "regNr", regNr }
};

var url = ToQueryString(Request.Url.PathAndQuery, queryParams);