UrlDecodeQueryFeature.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using MediaBrowser.Common.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. // Unencode and re-parse querystring.
  50. var unencodedKey = HttpUtility.UrlDecode(key);
  51. if (string.Equals(unencodedKey, key, System.StringComparison.Ordinal))
  52. {
  53. // Don't do anything if it's not encoded.
  54. _store = value;
  55. return;
  56. }
  57. var pairs = new Dictionary<string, StringValues>();
  58. var queryString = unencodedKey.SpanSplit('&');
  59. foreach (var pair in queryString)
  60. {
  61. var i = pair.IndexOf('=');
  62. if (i == -1)
  63. {
  64. // encoded is an equals.
  65. pairs.Add(pair[..i].ToString(), StringValues.Empty);
  66. continue;
  67. }
  68. pairs.Add(pair[..i].ToString(), new StringValues(pair[(i + 1)..].ToString()));
  69. }
  70. _store = new QueryCollection(pairs);
  71. }
  72. }
  73. }
  74. }