2016-05-02 32 views
0

我試圖執行GET添加參數。我以前使用的WebClient代碼突然停止工作,所以我決定切換到使用HttpWebRequest/HttpWebResponse。你如何正確地添加參數?我有一個REST函數需要兩個字符串參數,但我無法看到它們。基本上,我如何向GET調用添加多個參數?HttpGet參數使用HttpWebResponse C#

這裏是我的獲取代碼(booksString是一個逗號分隔的書籍ID的字符串):

string webAddress = "http://localhost:5000/stuff/address"; 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddress); 
request.Headers.Add("bookIds", booksString); 
request.Method = "GET"; 
request.Accept = "text/html"; 
request.KeepAlive = true; 
request.ProtocolVersion = HttpVersion.Version10; 
string text = ""; 
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
{ 
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), 
      Encoding.ASCII)) 
    { 
     text = reader.ReadToEnd(); 
    } 
} 
Console.WriteLine("text: " + text); 

,這裏是我的REST代碼:

public List<Book> GetBooks(string bookIds, string param2) 
{ 
    Console.WriteLine("book IDs: " + bookIds + " " + param2); 
} 

每當我運行此代碼bookIds是空的?如何發送多個參數並讓我的REST功能識別數據?

+0

嘗試使用URL發送請求,例如http:// localhost:5000/stuff/address?bookIds = value&param2 = value – Hakunamatata

+0

對我來說看起來並不像休息。看起來像一個普通的方法。 –

回答

0

嘗試使用RestSharp Nuget包,它非常整齊地封裝HTTPWeb請求。

在你能做到這一點

var baseUrl = "http://localhost:5000/"; 
var resource = "stuff/address"; 
var api = new RestClient(baseUrl); 
var request = new RestRequest(resource, Method.GET); 
request.AddQueryParameter("bookIds", bookString); 
request.AddQueryParameter("param2", value); 
api.Execute(request);