我正在尝试创建我的 Web 应用程序并且我想连接到 API。我的Startup.cs
文件中有基地址:
services.AddHttpClient("API Client", client =>
{
client.BaseAddress = new Uri("https://icanhazdadjoke.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
但是现在我想通过/search
在 url 地址中添加一个来更改它。我正在使用UriBuilder
,它看起来像这样:
string responseBody = "";
var client = _httpClientFactory.CreateClient("API Client");
var builder = new UriBuilder(client.GetAsync("") + "/search");
var query = HttpUtility.ParseQueryString(builder.Query);
query.Add("term", searchedTerm);
query.Add("limit", jokesPerPage);
builder.Query = query.ToString();
string url = builder.ToString();
responseBody = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject<JokeModel>(responseBody);
我收到一个错误:
UriFormatException:无效的 URI:无法解析主机名。
我怎样才能解决这个问题?