簡體   English   中英

HttpClient.GetAsync,無效的URI異常

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM