I’m currently using RestSharp as a client for downloading product details, however it appears that the response from the server (which I have no control over) is encoded in a differerent character set (ISO-8859-1) than RestSharp is expecting (UTF-8). This means that although most characters are converted as expected, some such as accents have no match and are displayed as mystery characters.

"name": "OASIS Silver Diamant� Toe Post Sandals"

The expected value is

"name": "OASIS Silver Diamanté Toe Post Sandals"

It doesn’t seem possible to set the encoding on the RestClient, though it is possible to decode the RawBytes from the response properly with the expected encoding.

In order to avoid having to decode the response in your code after each time it’s called you can use the OnBeforeDeserialization function on the request to automatically convert the bytes correctly before the response is deserialized.

public Product GetProductDetails(string sku)
{
	var request = new RestRequest("api/v2/product/{sku}", Method.GET);
	request.AddParameter("sku", sku, ParameterType.UrlSegment);

	request.OnBeforeDeserialization = response =>
	{
		Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
		response.Content = encoding.GetString(response.RawBytes);
	};

	try
	{
		return _baseClient.MakeRequest<Product>(request);
	}
	catch (Exception ex)
	{
		_logger.LogWarning(ex, "Failed to get product details");
		return new Product(sku);
	}
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *