HttpClient从API返回html

问题描述 投票:0回答:1

[尝试使用HttpClient从API获取json响应,但不断获取html响应。在浏览器和Postman中,我只需输入url就可以在json中得到结果。当使用RestSharp时,我也会在json中获得响应。我需要添加什么才能在json中获得响应?

我使用.net core 3.1。

这里是代码:

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;
    }
}
c# .net .net-core dotnet-httpclient
1个回答
1
投票

作为旁注,您可能需要考虑将HttpClient声明为静态。建议在its documentation中使用。另外,如果要使用json,则需要使用DeserializeObject方法:

var result = JsonConvert.DeserializeObject<RootObject>(responseString);

[您只需要确保已经从Nuget软件包安装了Newtonsoft.Json,并将以下内容添加到了using指令中:

using Newtonsoft.Json;
© www.soinside.com 2019 - 2024. All rights reserved.