3

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()
DavidG
  • 113,891
  • 12
  • 217
  • 223
Ashish
  • 59
  • 1
  • 4
  • Providing [MCVE] is very important for "why this error happens". I.e. in this case it should be one line `var uri = new Uri("api/products/" + "productId");` (also I understand that it may be painfully clear what the problem is - but "minimal" is important part). – Alexei Levenkov Oct 23 '15 at 00:38
  • If your question is more about using BaseAddress (like http://stackoverflow.com/questions/23438416/why-is-httpclient-baseaddress-not-working) you may want to clarify that. – Alexei Levenkov Oct 23 '15 at 00:41
  • @AlexeiLevenkov I provided the complete method because I have seen many people asking for it. – Ashish Oct 23 '15 at 00:46

1 Answers1

2

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());
Ashish
  • 59
  • 1
  • 4