Ashish
Ashish

Reputation: 59

HttpClient.GetAsync, Invalid URI exception

The below mentioned code doesn't work. I get the following exception in GetAsync:

Invalid URI: The format of the URI could not be determined.

However, if I comment the apiClient.BaseAddress and specify the full URI in apiClient.GetAsync then it works fine!

Could someone please explain the reason?

DEV Environment: VS2012, .NET 4.5, C#, ASP.NET WebForms

Code

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

Upvotes: 3

Views: 4662

Answers (1)

Ashish
Ashish

Reputation: 59

Found the issue with the help of another post on StackOverflow. Thanks @Alexei for the URL.

Changed the URI string and it works fine.

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

Upvotes: 2

Related Questions