Search code examples
c#apiuribuilder

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


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?


Solution

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