UriFormatException:无效的 URI:无法解析主机名。 MVC API C#

UriFormatException: Invalid URI: The hostname could not be parsed. MVC API C#

我正在尝试创建我的 Web 应用程序并且我想连接到 API。我的 Startup.cs 文件中有基址:

services.AddHttpClient("API Client", client =>
{
    client.BaseAddress = new Uri("https://icanhazdadjoke.com/");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

但现在我想在程序中通过在url 地址中添加一个/search 来更改它。我正在使用 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: Invalid URI: The hostname could not be parsed.

我该如何解决这个问题?

GetAsync 执行 GET 请求,而您可能想使用客户端的 BaseAddress 作为初始 Uri 来构造:

var builder = new UriBuilder(client.BaseAddress);
builder.Path = "/search";
var query = HttpUtility.ParseQueryString(builder.Query);
query.Add("term", searchedTerm);
query.Add("limit", jokesPerPage);

builder.Query = query.ToString();
string url = builder.ToString();