0

Why the response doesn't contain Content-Encoding header?

using System.Net;
using System.Text;

namespace MyServer
{
    class Program
    {
        static void Main(string[] args)
        {
           var listener = new HttpListener();
           listener.Prefixes.Add("http://localhost:8001/");
           listener.Start();
           var context = listener.GetContext();
           var response = context.Response;
           response.ContentEncoding = Encoding.UTF8;
           response.ContentType = "application/json";
           var json = "{'message':'Привет, мир!'}";
           var jsonBytes = response.ContentEncoding.GetBytes(json);
           response.ContentLength64 = jsonBytes.LongLength;
           response.StatusCode = (int)HttpStatusCode.OK;
           response.OutputStream.Write(jsonBytes,0,jsonBytes.Length);
           response.OutputStream.Close();
        }
    }
}

enter image description here

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • Does this answer your question? [Is content-encoding being set to UTF-8 invalid?](https://stackoverflow.com/questions/17154967/is-content-encoding-being-set-to-utf-8-invalid) – Pavel Anikhouski Jun 22 '20 at 07:44
  • @PavelAnikhouski, no. `HttpListenerResponse.ContentEncoding` property has `Encoding type`. – Andrey Bushman Jun 22 '20 at 17:56

2 Answers2

1

UTF-8 is not a valid content encoding in this case.

See also: Is content-encoding being set to UTF-8 invalid?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding

Content-Encoding: gzip
Content-Encoding: compress
Content-Encoding: deflate
Content-Encoding: identity
Content-Encoding: br

// Multiple, in the order in which they were applied
Content-Encoding: gzip, identity
Content-Encoding: deflate, gzip
Alex AIT
  • 17,361
  • 3
  • 36
  • 73
  • Hm... But `HttpListenerResponse.ContentEncoding` property has `Encoding` type. It can't to be *gzip*, *compress*, etc. It seems that in .NET this property should point to the encoding. – Andrey Bushman Jun 22 '20 at 17:48
1

Also, you could specify encoding like this

response.ContentType = "application/json; charset=utf-8";

See more at What does "Content-type: application/json; charset=utf-8" really mean?

But like it is said there : charset for json response is redundant

Roman Kalinchuk
  • 718
  • 3
  • 14