[英]HttpClient.GetAsync, Invalid URI exception
下面提到的代碼不起作用。 我在GetAsync
得到以下異常:
無效的URI:無法確定URI的格式。
但是,如果我評論的apiClient.BaseAddress
並指定完整URI中apiClient.GetAsync
然后正常工作!
有人可以解釋原因嗎?
DEV環境: VS2012,.NET 4.5,C#,ASP.NET WebForms
碼
private async Task WebAPICall()
{
using (var apiClient = new HttpClient())
{
apiClient.BaseAddress = new Uri("http://localhost:9000/");
apiClient.DefaultRequestHeaders.Accept.Clear();
apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
apiClient.Timeout = new TimeSpan(0, 0, 30);
try
{
HttpResponseMessage apiResponseMsg = await apiClient.GetAsync(new Uri("api/products/" + txtProductID.Text.Trim()));
string strResponse = await apiResponseMsg.Content.ReadAsStringAsync();
Response.Write(strResponse);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
} //using (var apiClient = new HttpClient())
} //private async Task WebAPICall()
在StackOverflow的另一篇文章的幫助下找到了這個問題。 感謝@Alexei提供的URL。
更改了URI字符串,它工作正常。
HttpResponseMessage apiResponseMsg = await apiClient.GetAsync("api/products/" + txtProductID.Text.Trim());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.