[尝试使用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;
}
}
作为旁注,您可能需要考虑将HttpClient
声明为静态。建议在its documentation中使用。另外,如果要使用json,则需要使用DeserializeObject
方法:
var result = JsonConvert.DeserializeObject<RootObject>(responseString);
[您只需要确保已经从Nuget软件包安装了Newtonsoft.Json
,并将以下内容添加到了using
指令中:
using Newtonsoft.Json;