UrlDecodeQueryFeature.cs 2.7 KB

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