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

前端 未结 30 2552
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  臣服心动
    2020-11-22 02:39

    How about creating extension methods that allow you to add the parameters in a fluent style like this?

    string a = "http://www.somedomain.com/somepage.html"
        .AddQueryParam("A", "TheValueOfA")
        .AddQueryParam("B", "TheValueOfB")
        .AddQueryParam("Z", "TheValueOfZ");
    
    string b = new StringBuilder("http://www.somedomain.com/anotherpage.html")
        .AddQueryParam("A", "TheValueOfA")
        .AddQueryParam("B", "TheValueOfB")
        .AddQueryParam("Z", "TheValueOfZ")
        .ToString(); 
    

    Here's the overload that uses a string:

    public static string AddQueryParam(
        this string source, string key, string value)
    {
        string delim;
        if ((source == null) || !source.Contains("?"))
        {
            delim = "?";
        }
        else if (source.EndsWith("?") || source.EndsWith("&"))
        {
            delim = string.Empty;
        }
        else
        {
            delim = "&";
        }
    
        return source + delim + HttpUtility.UrlEncode(key)
            + "=" + HttpUtility.UrlEncode(value);
    }
    

    And here's the overload that uses a StringBuilder:

    public static StringBuilder AddQueryParam(
        this StringBuilder source, string key, string value)
    {
        bool hasQuery = false;
        for (int i = 0; i < source.Length; i++)
        {
            if (source[i] == '?')
            {
                hasQuery = true;
                break;
            }
        }
    
        string delim;
        if (!hasQuery)
        {
            delim = "?";
        }
        else if ((source[source.Length - 1] == '?')
            || (source[source.Length - 1] == '&'))
        {
            delim = string.Empty;
        }
        else
        {
            delim = "&";
        }
    
        return source.Append(delim).Append(HttpUtility.UrlEncode(key))
            .Append("=").Append(HttpUtility.UrlEncode(value));
    }
    

提交回复
热议问题