HttpClient.GetAsync,无效的URI异常

时间:2015-10-23 00:15:15

标签: c# asp.net asp.net-web-api httpclient getasync

下面提到的代码不起作用。我在GetAsync中收到以下异常:

  

无效的URI:无法确定URI的格式。

但是,如果我评论apiClient.BaseAddress并在apiClient.GetAsync中指定完整的URI,那么它可以正常工作!

有人可以解释原因吗?

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()

1 个答案:

答案 0 :(得分:2)

在StackOverflow上的另一篇文章的帮助下发现了这个问题。感谢@Alexei提供的URL。

更改了URI字符串,它工作正常。

HttpResponseMessage apiResponseMsg = await apiClient.GetAsync("api/products/" + txtProductID.Text.Trim());