UrlDecodeQueryFeature.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Web;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Http.Features;
  6. using Microsoft.Extensions.Primitives;
  7. namespace Jellyfin.Server.Middleware
  8. {
  9. /// <summary>
  10. /// Defines the <see cref="UrlDecodeQueryFeature"/>.
  11. /// </summary>
  12. public class UrlDecodeQueryFeature : IQueryFeature
  13. {
  14. private IQueryCollection? _store;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
  17. /// </summary>
  18. /// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
  19. public UrlDecodeQueryFeature(IQueryFeature feature)
  20. {
  21. Query = feature.Query;
  22. }
  23. /// <summary>
  24. /// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
  25. /// </summary>
  26. public IQueryCollection Query
  27. {
  28. get
  29. {
  30. return _store ?? QueryCollection.Empty;
  31. }
  32. set
  33. {
  34. // Only interested in where the querystring is encoded which shows up as one key with everything else in the value.
  35. if (value.Count != 1)
  36. {
  37. _store = value;
  38. return;
  39. }
  40. // Encoded querystrings have no value, so don't process anything if a values is present.
  41. var kvp = value.First();
  42. if (!string.IsNullOrEmpty(kvp.Value))
  43. {
  44. _store = value;
  45. return;
  46. }
  47. // Unencode and re-parse querystring.
  48. var unencodedKey = HttpUtility.UrlDecode(kvp.Key);
  49. if (string.Equals(unencodedKey, kvp.Key, System.StringComparison.Ordinal))
  50. {
  51. _store = value;
  52. return;
  53. }
  54. var pairs = new Dictionary<string, StringValues>();
  55. var queryString = unencodedKey.Split('&', System.StringSplitOptions.RemoveEmptyEntries);
  56. foreach (var pair in queryString)
  57. {
  58. var item = pair.Split('=', System.StringSplitOptions.RemoveEmptyEntries);
  59. pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty));
  60. }
  61. _store = new QueryCollection(pairs);
  62. }
  63. }
  64. }
  65. }