'UTF8' is not a supported encoding name

2019-04-19 10:16发布

So I'm just playing around with Spotify's Web API and I'm trying to access my top played tracks. Although I've encountered a problem I've been trying to solve for a couple of hours now but I can't find an answer.

When I try to deserialize my response, I get the follwing error:

'UTF8' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. Parameter name: name The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.

The ContentType is application/json; charset=UTF8

Any ideas?

Here's my request code:

private static HttpClient GetHttpClient()
{
    HttpClientHandler handler = new HttpClientHandler() {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
    };
    var httpClient = new HttpClient(handler);
    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
    return httpClient;
}

public async Task<SearchArtistResponse> GetSelfTopAsync(string type, string userName)
{
    var httpClient = GetHttpClient();
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken(userName));

    var sb = new StringBuilder();
    sb.Append(ApiUrl);
    sb.Append($"/me/top/{type}");
    var query = sb.ToString();
    var response = await httpClient.GetAsync(query);

    var spotifyResponse = JsonConvert.DeserializeObject<SearchArtistResponse>(await response.Content.ReadAsStringAsync());
    return spotifyResponse;
}

标签: c# utf-8 spotify
2条回答
Anthone
2楼-- · 2019-04-19 10:41

Are you using .net core?

You will need to add the following code to make the encodings available in .NET desktop available in your environment:

System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);

More info on CodePagesEncodingProvider.Instance can be found here.

查看更多
相关推荐>>
3楼-- · 2019-04-19 10:56

The problem should be a validation of response header Content-Type ,that occur when you call ReadAsStringAsync(), if you call ReadAsByteArrayAsync() instead and parse to string

(System.Text.Encoding.UTF8.GetString())

that will gonna work!!!

查看更多
登录 后发表回答