HttpContextDebugFormatter.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. using System.Globalization;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Http.Features;
  6. namespace Microsoft.AspNetCore.Shared;
  7. internal static class HttpContextDebugFormatter
  8. {
  9. public static string ResponseToString(HttpResponse response, string? reasonPhrase)
  10. {
  11. var text = response.StatusCode.ToString(CultureInfo.InvariantCulture);
  12. var resolvedReasonPhrase = ResolveReasonPhrase(response, reasonPhrase);
  13. if (!string.IsNullOrEmpty(resolvedReasonPhrase))
  14. {
  15. text += $" {resolvedReasonPhrase}";
  16. }
  17. if (!string.IsNullOrEmpty(response.ContentType))
  18. {
  19. text += $" {response.ContentType}";
  20. }
  21. return text;
  22. }
  23. private static string? ResolveReasonPhrase(HttpResponse response, string? reasonPhrase)
  24. {
  25. return response.HttpContext.Features.Get<IHttpResponseFeature>()?.ReasonPhrase ?? reasonPhrase;
  26. }
  27. public static string RequestToString(HttpRequest request)
  28. {
  29. var text = $"{request.Method} {GetRequestUrl(request, includeQueryString: true)} {request.Protocol}";
  30. if (!string.IsNullOrEmpty(request.ContentType))
  31. {
  32. text += $" {request.ContentType}";
  33. }
  34. return text;
  35. }
  36. public static string ContextToString(HttpContext context, string? reasonPhrase)
  37. {
  38. var text = $"{context.Request.Method} {GetRequestUrl(context.Request, includeQueryString: false)} {context.Response.StatusCode}";
  39. var resolvedReasonPhrase = ResolveReasonPhrase(context.Response, reasonPhrase);
  40. if (!string.IsNullOrEmpty(resolvedReasonPhrase))
  41. {
  42. text += $" {resolvedReasonPhrase}";
  43. }
  44. return text;
  45. }
  46. private static string GetRequestUrl(HttpRequest request, bool includeQueryString)
  47. {
  48. return $"{request.Scheme}://{request.Host.Value}{request.PathBase.Value}{request.Path.Value}{(includeQueryString ? request.QueryString.Value : string.Empty)}";
  49. }
  50. }