C# 解決httplistener querystring 中文亂碼、返回json中文格式亂碼

zmxyzmxy1234發表於2021-04-27

解決httplistener querystring 中文亂碼方案:

在請求到達時候,獲取Request.Url,返回get請求引數 鍵值對

    public class RequestHelper
    {
        public static Dictionary<string, string> EncodeQueryString(Uri uri)
        {
            var ret = new Dictionary<string, string>();
            var q = uri.Query;
            if (q.Length > 0)
            {
                foreach (var p in q.Substring(1).Split('&'))
                {
                    var s = p.Split(new char[] { '=' }, 2);
                    ret.Add(HttpUtility.UrlDecode(s[0]), HttpUtility.UrlDecode(s[1]));
                }
            }
            return ret;
        }
    }

解決返回json中文格式亂碼:

對中午json字串進行編碼 HttpUtility.UrlDecode(“中文”);

  public class ResponseHelper
    {
        public static void Respose(HttpListenerResponse response, string jsonStr = "")
        {
            byte[] buffer = Encoding.UTF8.GetBytes(jsonStr);
            response.ContentLength64 = buffer.Length;
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.StatusCode = 200;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            //關閉輸出流,釋放相應資源
            output.Close();
            response.Close();
        }
    }

轉載於:連結

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章