Search code examples
c#.net.net-coredotnet-httpclient

HttpClient returns html from API


Trying to use the HttpClient to get a json response from an API but keep getting html response. In the browser and in Postman I get the result in json just by typing in the url. When using RestSharp I also get the response in json. What do I need to add to get the response in json? The variable responseString in a html string, not a json string.

I use .net core 3.1.

Here's the code:

class Program
{
    static async Task Main(string[] args)
    {
        var response = await GetResponse();
        System.Console.ReadKey();
    }

    public static async Task<string> GetResponse()
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://musicbrainz.org/ws/2/");

        client.DefaultRequestHeaders.Add("Accept",
            "application/json");

        using var response = await client.GetAsync((
            "/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json&inc=url-rels+release-groups"));

        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }
}

Solution

  • I think the API is looking for a User-Agent.

    Try to Add

    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36")