ExtensionMethods.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.IO;
  2. using System.IO.Compression;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace FNZCM.ConHost
  8. {
  9. internal static class ExtensionMethods
  10. {
  11. public static void WriteTextUtf8(this HttpListenerContext context, string content, string contentType = Const.TextHtml)
  12. {
  13. var bytes = Encoding.UTF8.GetBytes(content);
  14. context.Response.ContentEncoding = Encoding.UTF8;
  15. context.Response.ContentType = contentType;
  16. if (true == context.Request.Headers["Accept-Encoding"]?.Contains("gzip"))
  17. {
  18. context.Response.AddHeader("Content-Encoding", "gzip");
  19. var memoryStream = new MemoryStream(bytes);
  20. var gZipStream = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, false);
  21. memoryStream.CopyTo(gZipStream);
  22. gZipStream.Flush();
  23. }
  24. else
  25. {
  26. context.Response.OutputStream.Write(bytes);
  27. }
  28. }
  29. public static string ToMd5(this string s)
  30. {
  31. var bytes = Encoding.UTF8.GetBytes(s);
  32. var md5 = MD5.Create();
  33. var hash = md5.ComputeHash(bytes);
  34. var hex = string.Join("", hash.Select(p => p.ToString("x2")));
  35. return hex;
  36. }
  37. }
  38. }