[英]C# HttpClient Uri value
我正在創建WindowsPhone 8.1應用程序,但無法讓客戶端訪問數據庫。 我創建了一個服務器端項目,可以使用Web api正常運行。 我能夠運行調試器並添加“ / api / entityName”以返回該表中所有行的列表,或者如果我指定了id值,則僅返回一行。 在客戶端進行了大量測試之后,我認為我已經指出了我的錯誤:uri值。 有人可以告訴我應該將什么值傳遞給uri構造函數嗎? 這是我在客戶端中使用的方法:
public async void GetBars()
{
var uri = new Uri("http://localhost:20672/tables/bars"); //seems like this value is the problem
var httpClient = new HttpClient();
barsListBox.Items.Add("right before try starts");
// Always catch network exceptions for async methods
try
{
barsListBox.Items.Add("try started");
var result = await httpClient.GetStringAsync(uri); //never gets past this line. goes straight to finally
barsListBox.Items.Add("right before linq");
var queryAllBars =
from bar in result
select bar;
barsListBox.Items.Add("linq finished");
foreach (var bar in queryAllBars)
{
barsListBox.Items.Add(bar);
}
}
catch
{
// Details in ex.Message and ex.HResult.
}
finally
{
barsListBox.Items.Add("finally executed");
httpClient.Dispose();
}
}
該數據庫是托管在Azure上的SQL Server數據庫。 我嘗試使用Azure中為數據庫列出的URL,我當前的IP地址,幾乎使用/排除端口號的每種組合等,但是似乎沒有任何效果。 我沒有任何錯誤,但是我也沒有在用戶界面中顯示任何內容(輸入的測試語句除外)。 嘗試開始打印,但是在linq之前不會打印,這就是為什么我認為我的問題來自傳遞給int GetStringAsync的uri值。 謝謝您的幫助。
你可以這樣嘗試
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://Ipaddress/mammo/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/controllername");
if (response.IsSuccessStatusCode)
{
IList<something> data = await response.Content.ReadAsAsync<IList<something>>();
}
}
感謝@Midhun的回答和我收到的其他回答,我得以使這些條正確打印。 我在托管數據庫的uri(azurewebsites.net url)而非本地數據庫中使用了Midhun的代碼。 我還將IList更改為String,並編寫了一種使用IndexOf和Substring挑選值的方法,如下所示:
start = bar.IndexOf("BarID", start) + 7;
int end = bar.IndexOf(",", start);
int id = Convert.ToInt32(bar.Substring(start, (end - start)));
Bars newBar = new Bars(id, name, street, city, state, phone, zip);
Bars.barsList.Add(newBar);
然后,我在Bars模型中創建了一個靜態列表,以向其中添加新創建的Bars項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.