【发布时间】:2015-10-23 00:15:15
【问题描述】:
下面提到的代码不起作用。我在GetAsync 中得到以下异常:
无效的 URI:无法确定 URI 的格式。
但是,如果我评论 apiClient.BaseAddress 并在 apiClient.GetAsync 中指定完整的 URI,那么它可以正常工作!
有人能解释一下原因吗?
开发环境: 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()
【问题讨论】:
-
提供minimal reproducible example 对于“为什么会发生此错误”非常重要。 IE。在这种情况下,它应该是一行
var uri = new Uri("api/products/" + "productId");(我也明白,问题出在哪里可能很痛苦——但“最小”是重要的部分)。 -
如果您的问题更多是关于使用 BaseAddress(如 stackoverflow.com/questions/23438416/…),您可能需要澄清一下。
-
@AlexeiLevenkov 我提供了完整的方法,因为我看到很多人要求它。
标签: c# asp.net asp.net-web-api httpclient getasync