LoginSignup
11
12

More than 5 years have passed since last update.

URIの?以降に&でつなげたクエリー文字列を生成する

Posted at

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

LINQを使う

private string ToQueryString(NameValueCollection nvc)
{
  return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
}

HttpUtility.ParseQueryStringを使う

UTF-8エンコードまでしてくれるらしい
https://msdn.microsoft.com/ja-jp/library/ms150046(v=vs.110).aspx

NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);

queryString["key1"] = "value1";
queryString["key2"] = "value2";

return queryString.ToString(); // URLエンコードされた "key1=value1&key2=value2"が返る
11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12