Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The character set provided in ContentType is invalid

Tags:

c#

.net-core

I wrote some simple code with async await, but when I try to run it, the compiler throws a System.InvalidOperationException.

The full error message is:

Unhandled Exception: System.InvalidOperationException: The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.

System.ArgumentException: 'ISO-8859-2' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

The code:

class Program
{
    static async Task Main(string[] args) => await asyncDoItAsync();

    private static async Task<string> asyncDoItAsync()
    {
        HttpClient client = new HttpClient(); 
        Task<string> url = client.GetStringAsync("http://google.pl");

        while(!url.IsCompleted)
        {
            WhenWaiting();
        }

        string url_length  = await url;

        return url_length;
    }

    private static void WhenWaiting()
    {
        Console.WriteLine("Waiting ...");
        Thread.Sleep(90);
    }
}
like image 671
Karol Pisarzewski Avatar asked Apr 14 '18 06:04

Karol Pisarzewski


2 Answers

GetStringAsync does not seem to support iso-8859 in the response, and it's basically nothing you can do about it. So you need to start with GetAsync instead. Be sure to clear your existing headers or it probably will still fail. Below works for me for the url you provided (although I'm using ISO-8859-1 and not 2):

var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
string s = null;
var result = await client.GetAsync("http://google.pl");
using (var sr = new StreamReader(await result.Content.ReadAsStreamAsync(), Encoding.GetEncoding("iso-8859-1")))
{
     s = sr.ReadToEnd();
}
like image 135
Gustav Avatar answered Nov 11 '22 00:11

Gustav


In .NET Core not all code pages are available by default. See this answer here for details on how to enable more.

Basically, install the System.Text.Encoding and System.Text.Encoding.CodePages packages from Nuget, and then include this line before running any http requests:

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
like image 27
ketura Avatar answered Nov 10 '22 23:11

ketura