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

前端 未结 30 2925
借酒劲吻你
借酒劲吻你 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:32

    I added the following method to my PageBase class.

    protected void Redirect(string url)
        {
            Response.Redirect(url);
        }
    protected void Redirect(string url, NameValueCollection querystrings)
        {
            StringBuilder redirectUrl = new StringBuilder(url);
    
            if (querystrings != null)
            {
                for (int index = 0; index < querystrings.Count; index++)
                {
                    if (index == 0)
                    {
                        redirectUrl.Append("?");
                    }
    
                    redirectUrl.Append(querystrings.Keys[index]);
                    redirectUrl.Append("=");
                    redirectUrl.Append(HttpUtility.UrlEncode(querystrings[index]));
    
                    if (index < querystrings.Count - 1)
                    {
                        redirectUrl.Append("&");
                    }
                }
            }
    
            this.Redirect(redirectUrl.ToString());
        }
    

    To call:

    NameValueCollection querystrings = new NameValueCollection();    
    querystrings.Add("language", "en");
    querystrings.Add("id", "134");
    this.Redirect("http://www.mypage.com", querystrings);
    

提交回复
热议问题