RestSharp ignores response charset encoding

2019-02-19 08:43发布

问题:

I'm using RestSharp version 105.1.0 (.NET 4.5.1) to make a REST call to our own API. This API sends responses with the following header of particular interest: Content-Type: application/json; Charset=iso-8859-1. As you can see, the charset of this response is set to iso-8859-1.

I would expect that the response I get from RestSharp uses this encoding to decode the response content. However, when I look at the RestResponse.Content property, some characters display as �. As far as i know this means the wrong encoding was used. When I try decoding the RawBytes manually using the proper encoding, I do get the correct string.

I tried manually setting the iso-8859-1 Encoding property on the RestClient but to no avail.

How can I make sure the responses from RestSharp are decoded using the right encoding?

Example code:

// Setting the Encoding here does not change the result
var client = new RestClient(myApiUri) { Encoding = Encoding.GetEncoding("iso-8859-1") };
var request = new RestRequest(Method.GET);
var restResponse = client.Execute(request);
Console.WriteLine(restResponse.Content)
// Outputs content as string with wrong encoding
// some characters display as �

Thanks in advance!

回答1:

I also had this problem, to solve had to get the byte array that it brings in IRestResponse object and convert it to encode I want

var request = new RestRequest(Method.GET);
var restResponse = client.Execute(request);

Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
var result = encoding.GetString(response.RawBytes);
Console.WriteLine(result);