0

I am trying to create my web application and I want to connect to API. I have base address in my Startup.cs file:

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

But now I want to change it in program by adding a /search to the url address. I am using UriBuilder and it looks like this:

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);

I got an error:

UriFormatException: Invalid URI: The hostname could not be parsed.

How can I fix this?

stasiaks
  • 1,268
  • 2
  • 14
  • 31
  • Is server secure (https) or non secure (http)? If secure, you are failing the SSL/TLS certification. – jdweng Apr 27 '20 at 18:38

1 Answers1

0

GetAsync executes a GET request whereas you presumably want to use the client's BaseAddress as the initial Uri to construct:

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();
Lee
  • 142,018
  • 20
  • 234
  • 287