UserAgentDelegatingHandler.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Net.Http;
  3. using System.Net.Http.Headers;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace MediaBrowser.Common.Net
  7. {
  8. /// <summary>
  9. /// User agent delegating handler.
  10. /// Adds User-Agent header to all requests.
  11. /// </summary>
  12. public class UserAgentDelegatingHandler : DelegatingHandler
  13. {
  14. private readonly ProductInfoHeaderValue[] _userAgentValues;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="UserAgentDelegatingHandler"/> class.
  17. /// </summary>
  18. /// <param name="applicationHost">Instance of the <see cref="IApplicationHost"/> interface.</param>
  19. public UserAgentDelegatingHandler(IApplicationHost applicationHost)
  20. {
  21. _userAgentValues = new[]
  22. {
  23. new ProductInfoHeaderValue(applicationHost.Name.Replace(' ', '-'), applicationHost.ApplicationVersionString),
  24. new ProductInfoHeaderValue($"({Environment.OSVersion}; {applicationHost.ApplicationUserAgentAddress})")
  25. };
  26. }
  27. /// <summary>
  28. /// Send request message.
  29. /// </summary>
  30. /// <param name="request">The request message.</param>
  31. /// <param name="cancellationToken">The cancellation token.</param>
  32. /// <returns>A <see cref="Task"/> containing the <see cref="HttpResponseMessage"/>.</returns>
  33. protected override Task<HttpResponseMessage> SendAsync(
  34. HttpRequestMessage request,
  35. CancellationToken cancellationToken)
  36. {
  37. if (request.Headers.UserAgent.Count == 0)
  38. {
  39. for (var i = 0; i < _userAgentValues.Length; i++)
  40. {
  41. request.Headers.UserAgent.Add(_userAgentValues[i]);
  42. }
  43. }
  44. return base.SendAsync(request, cancellationToken);
  45. }
  46. }
  47. }