UrlDecodeQueryFeature.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using Jellyfin.Extensions;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Http.Features;
  8. using Microsoft.Extensions.Primitives;
  9. namespace Jellyfin.Server.Middleware
  10. {
  11. /// <summary>
  12. /// Defines the <see cref="UrlDecodeQueryFeature"/>.
  13. /// </summary>
  14. public class UrlDecodeQueryFeature : IQueryFeature
  15. {
  16. private IQueryCollection? _store;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
  19. /// </summary>
  20. /// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
  21. public UrlDecodeQueryFeature(IQueryFeature feature)
  22. {
  23. Query = feature.Query;
  24. }
  25. /// <summary>
  26. /// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
  27. /// </summary>
  28. public IQueryCollection Query
  29. {
  30. get
  31. {
  32. return _store ?? QueryCollection.Empty;
  33. }
  34. set
  35. {
  36. // Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
  37. if (value.Count != 1)
  38. {
  39. _store = value;
  40. return;
  41. }
  42. // Encoded querystrings have no value, so don't process anything if a value is present.
  43. var (key, stringValues) = value.First();
  44. if (!string.IsNullOrEmpty(stringValues))
  45. {
  46. _store = value;
  47. return;
  48. }
  49. var pairs = new Dictionary<string, StringValues>();
  50. var queryString = HttpUtility.UrlDecode(key).SpanSplit('&');
  51. foreach (var pair in queryString)
  52. {
  53. var i = pair.IndexOf('=');
  54. if (i == -1)
  55. {
  56. // encoded is an equals.
  57. // We use TryAdd so duplicate keys get ignored
  58. pairs.TryAdd(pair.ToString(), StringValues.Empty);
  59. continue;
  60. }
  61. var k = pair[..i].ToString();
  62. var v = pair[(i + 1)..].ToString();
  63. if (!pairs.TryAdd(k, new StringValues(v)))
  64. {
  65. pairs[k] = StringValues.Concat(pairs[k], v);
  66. }
  67. }
  68. _store = new QueryCollection(pairs);
  69. }
  70. }
  71. }
  72. }