UrlDecodeQueryFeature.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 nothing 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 value 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. // Don't do anything if it's not encoded.
  52. _store = value;
  53. return;
  54. }
  55. var pairs = new Dictionary<string, StringValues>();
  56. var queryString = unencodedKey.Split('&', System.StringSplitOptions.RemoveEmptyEntries);
  57. foreach (var pair in queryString)
  58. {
  59. var item = pair.Split('=', System.StringSplitOptions.RemoveEmptyEntries);
  60. if (item.Length > 0)
  61. {
  62. pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty));
  63. }
  64. else
  65. {
  66. pairs.Add(pair, string.Empty);
  67. }
  68. }
  69. _store = new QueryCollection(pairs);
  70. }
  71. }
  72. }
  73. }