在get方法中使用WebRequest对象提交数据

时间:2013-09-27 22:16:33

标签: c# get httpwebrequest webrequest

我有以下代码:

var Instance = WebRequest.Create(new Uri("http://mywebsite.com/page.aspx"));
var Data = new Dictionary<string, string>();
Data["Foo"] = "Bar";
Data["Baz"] = "Paz";

如何使用数据提交GET请求?

1 个答案:

答案 0 :(得分:1)

使用GET方法时,您应该将数据放入网址。

var Data = new Dictionary<string, string>();
Data["Foo"] = "Bar";
Data["Baz"] = "Paz";
UriBuilder uri = new UriBuilder("http://mywebsite.com/page.aspx");
uri.Query = String.Join("&",Data.Select(x=>String.Format("{0}={1}", 
                                          x.Key, HttpUtility.UrlEncode(x.Value))));


var Instance = WebRequest.Create(uri.ToString());

您的网址将是:

http://mywebsite.com:80/page.aspx?Foo=Bar&Baz=Paz