From 6bcc6c73405c13a23a5b3522727f80d677c40727 Mon Sep 17 00:00:00 2001 From: EagleMC Date: Thu, 10 Nov 2022 04:47:50 -0500 Subject: [PATCH] Add charset to response Content-Type Including the character set in the Content-Type header is generally needed to ensure correct display of Unicode characters. --- SimpleHttpServer/HttpProcessor.cs | 7 ++++++- SimpleHttpServer/Models/HttpResponse.cs | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/SimpleHttpServer/HttpProcessor.cs b/SimpleHttpServer/HttpProcessor.cs index 575584d..76916e5 100644 --- a/SimpleHttpServer/HttpProcessor.cs +++ b/SimpleHttpServer/HttpProcessor.cs @@ -71,7 +71,12 @@ private static void WriteResponse(Stream stream, HttpResponse response) { // default to text/html content type if (!response.Headers.ContainsKey("Content-Type")) { - response.Headers["Content-Type"] = "text/html"; + string type = "text/html"; + if (!string.IsNullOrWhiteSpace(response.CharsetName)) + { + type += "; charset=" + response.CharsetName; + } + response.Headers["Content-Type"] = type; } response.Headers["Content-Length"] = response.Content.Length.ToString(); diff --git a/SimpleHttpServer/Models/HttpResponse.cs b/SimpleHttpServer/Models/HttpResponse.cs index 3d963af..90ebbdc 100644 --- a/SimpleHttpServer/Models/HttpResponse.cs +++ b/SimpleHttpServer/Models/HttpResponse.cs @@ -39,6 +39,7 @@ public class HttpResponse public string StatusCode { get; set; } public string ReasonPhrase { get; set; } public byte[] Content { get; set; } + public string CharsetName { get; protected set; } public Dictionary Headers { get; set; } @@ -55,6 +56,7 @@ public void setContent(string content, Encoding encoding = null) { encoding = Encoding.UTF8; } + CharsetName = encoding.WebName; Content = encoding.GetBytes(content); }