When using HttpClient class in .NET, I found out when assigning the BaseAddress to HttpClient, the BaseAddress must end with "/". Otherwise it would get 404 error when calling the get or post method.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("Setting");
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
ilog.Error(string.Format("GetGlobalSetting error - StatusCode: {0}; ReasonPhrase: {1} ", response.StatusCode.ToString(), response.ReasonPhrase??""));
throw new Exception(string.Format("Error getting Global settings - StatusCode: {0}; ReasonPhrase: {1}", response.StatusCode.ToString(), response.ReasonPhrase ?? ""));
}
}
Comments