FortunesView.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Collections.Generic;
  2. using System.IO.Pipelines;
  3. using System.Web;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.Primitives;
  6. using PlatformBenchmarks;
  7. namespace appMpower
  8. {
  9. public static class FortunesView
  10. {
  11. private readonly static KeyValuePair<string, StringValues> _headerServer =
  12. new KeyValuePair<string, StringValues>("Server", "k");
  13. private readonly static KeyValuePair<string, StringValues> _headerContentType =
  14. new KeyValuePair<string, StringValues>("Content-Type", "text/html; charset=UTF-8");
  15. private readonly static AsciiString _fortunesTableStart = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
  16. private readonly static AsciiString _fortunesRowStart = "<tr><td>";
  17. private readonly static AsciiString _fortunesColumn = "</td><td>";
  18. private readonly static AsciiString _fortunesRowEnd = "</td></tr>";
  19. private readonly static AsciiString _fortunesTableEnd = "</table></body></html>";
  20. public static void Render(IHeaderDictionary headerDictionary, PipeWriter pipeWriter, List<Fortune> fortunes)
  21. {
  22. headerDictionary.Add(_headerServer);
  23. headerDictionary.Add(_headerContentType);
  24. var bufferWriter = new BufferWriter<WriterAdapter>(new WriterAdapter(pipeWriter), 1600);
  25. bufferWriter.Write(_fortunesTableStart);
  26. foreach (var fortune in fortunes)
  27. {
  28. bufferWriter.Write(_fortunesRowStart);
  29. bufferWriter.WriteNumeric((uint)fortune.Id);
  30. bufferWriter.Write(_fortunesColumn);
  31. bufferWriter.WriteUtf8String(HttpUtility.HtmlEncode(fortune.Message));
  32. bufferWriter.Write(_fortunesRowEnd);
  33. }
  34. bufferWriter.Write(_fortunesTableEnd);
  35. headerDictionary.Add(new KeyValuePair<string, StringValues>("Content-Length", bufferWriter.Buffered.ToString()));
  36. bufferWriter.Commit();
  37. }
  38. }
  39. }