HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Net;
  7. using System.Runtime.Serialization;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. using Emby.Server.Implementations.Services;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Net;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Serialization;
  17. using MediaBrowser.Model.Services;
  18. using Microsoft.Extensions.Logging;
  19. using Microsoft.Extensions.Primitives;
  20. using Microsoft.Net.Http.Headers;
  21. using IRequest = MediaBrowser.Model.Services.IRequest;
  22. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  23. namespace Emby.Server.Implementations.HttpServer
  24. {
  25. /// <summary>
  26. /// Class HttpResultFactory
  27. /// </summary>
  28. public class HttpResultFactory : IHttpResultFactory
  29. {
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. private readonly IFileSystem _fileSystem;
  35. private readonly IJsonSerializer _jsonSerializer;
  36. private readonly IStreamHelper _streamHelper;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  39. /// </summary>
  40. public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IStreamHelper streamHelper)
  41. {
  42. _fileSystem = fileSystem;
  43. _jsonSerializer = jsonSerializer;
  44. _streamHelper = streamHelper;
  45. _logger = loggerfactory.CreateLogger("HttpResultFactory");
  46. }
  47. /// <summary>
  48. /// Gets the result.
  49. /// </summary>
  50. /// <param name="content">The content.</param>
  51. /// <param name="contentType">Type of the content.</param>
  52. /// <param name="responseHeaders">The response headers.</param>
  53. /// <returns>System.Object.</returns>
  54. public object GetResult(IRequest requestContext, byte[] content, string contentType, IDictionary<string, string> responseHeaders = null)
  55. {
  56. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  57. }
  58. public object GetResult(string content, string contentType, IDictionary<string, string> responseHeaders = null)
  59. {
  60. return GetHttpResult(null, content, contentType, true, responseHeaders);
  61. }
  62. public object GetResult(IRequest requestContext, Stream content, string contentType, IDictionary<string, string> responseHeaders = null)
  63. {
  64. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  65. }
  66. public object GetResult(IRequest requestContext, string content, string contentType, IDictionary<string, string> responseHeaders = null)
  67. {
  68. return GetHttpResult(requestContext, content, contentType, true, responseHeaders);
  69. }
  70. public object GetRedirectResult(string url)
  71. {
  72. var responseHeaders = new Dictionary<string, string>();
  73. responseHeaders[HeaderNames.Location] = url;
  74. var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
  75. AddResponseHeaders(result, responseHeaders);
  76. return result;
  77. }
  78. /// <summary>
  79. /// Gets the HTTP result.
  80. /// </summary>
  81. private IHasHeaders GetHttpResult(IRequest requestContext, Stream content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  82. {
  83. var result = new StreamWriter(content, contentType);
  84. if (responseHeaders == null)
  85. {
  86. responseHeaders = new Dictionary<string, string>();
  87. }
  88. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string expires))
  89. {
  90. responseHeaders[HeaderNames.Expires] = "0";
  91. }
  92. AddResponseHeaders(result, responseHeaders);
  93. return result;
  94. }
  95. /// <summary>
  96. /// Gets the HTTP result.
  97. /// </summary>
  98. private IHasHeaders GetHttpResult(IRequest requestContext, byte[] content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  99. {
  100. string compressionType = null;
  101. bool isHeadRequest = false;
  102. if (requestContext != null)
  103. {
  104. compressionType = GetCompressionType(requestContext, content, contentType);
  105. isHeadRequest = string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  106. }
  107. IHasHeaders result;
  108. if (string.IsNullOrEmpty(compressionType))
  109. {
  110. var contentLength = content.Length;
  111. if (isHeadRequest)
  112. {
  113. content = Array.Empty<byte>();
  114. }
  115. result = new StreamWriter(content, contentType, contentLength);
  116. }
  117. else
  118. {
  119. result = GetCompressedResult(content, compressionType, responseHeaders, isHeadRequest, contentType);
  120. }
  121. if (responseHeaders == null)
  122. {
  123. responseHeaders = new Dictionary<string, string>();
  124. }
  125. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
  126. {
  127. responseHeaders[HeaderNames.Expires] = "0";
  128. }
  129. AddResponseHeaders(result, responseHeaders);
  130. return result;
  131. }
  132. /// <summary>
  133. /// Gets the HTTP result.
  134. /// </summary>
  135. private IHasHeaders GetHttpResult(IRequest requestContext, string content, string contentType, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  136. {
  137. IHasHeaders result;
  138. var bytes = Encoding.UTF8.GetBytes(content);
  139. var compressionType = requestContext == null ? null : GetCompressionType(requestContext, bytes, contentType);
  140. var isHeadRequest = requestContext == null ? false : string.Equals(requestContext.Verb, "head", StringComparison.OrdinalIgnoreCase);
  141. if (string.IsNullOrEmpty(compressionType))
  142. {
  143. var contentLength = bytes.Length;
  144. if (isHeadRequest)
  145. {
  146. bytes = Array.Empty<byte>();
  147. }
  148. result = new StreamWriter(bytes, contentType, contentLength);
  149. }
  150. else
  151. {
  152. result = GetCompressedResult(bytes, compressionType, responseHeaders, isHeadRequest, contentType);
  153. }
  154. if (responseHeaders == null)
  155. {
  156. responseHeaders = new Dictionary<string, string>();
  157. }
  158. if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
  159. {
  160. responseHeaders[HeaderNames.Expires] = "0";
  161. }
  162. AddResponseHeaders(result, responseHeaders);
  163. return result;
  164. }
  165. /// <summary>
  166. /// Gets the optimized result.
  167. /// </summary>
  168. /// <typeparam name="T"></typeparam>
  169. public object GetResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  170. where T : class
  171. {
  172. if (result == null)
  173. {
  174. throw new ArgumentNullException(nameof(result));
  175. }
  176. if (responseHeaders == null)
  177. {
  178. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  179. }
  180. responseHeaders[HeaderNames.Expires] = "0";
  181. return ToOptimizedResultInternal(requestContext, result, responseHeaders);
  182. }
  183. private string GetCompressionType(IRequest request, byte[] content, string responseContentType)
  184. {
  185. if (responseContentType == null)
  186. {
  187. return null;
  188. }
  189. // Per apple docs, hls manifests must be compressed
  190. if (!responseContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
  191. responseContentType.IndexOf("json", StringComparison.OrdinalIgnoreCase) == -1 &&
  192. responseContentType.IndexOf("javascript", StringComparison.OrdinalIgnoreCase) == -1 &&
  193. responseContentType.IndexOf("xml", StringComparison.OrdinalIgnoreCase) == -1 &&
  194. responseContentType.IndexOf("application/x-mpegURL", StringComparison.OrdinalIgnoreCase) == -1)
  195. {
  196. return null;
  197. }
  198. if (content.Length < 1024)
  199. {
  200. return null;
  201. }
  202. return GetCompressionType(request);
  203. }
  204. private static string GetCompressionType(IRequest request)
  205. {
  206. var acceptEncoding = request.Headers[HeaderNames.AcceptEncoding].ToString();
  207. if (string.IsNullOrEmpty(acceptEncoding))
  208. {
  209. //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
  210. // return "br";
  211. if (acceptEncoding.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  212. return "deflate";
  213. if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  214. return "gzip";
  215. }
  216. return null;
  217. }
  218. /// <summary>
  219. /// Returns the optimized result for the IRequestContext.
  220. /// Does not use or store results in any cache.
  221. /// </summary>
  222. /// <param name="request"></param>
  223. /// <param name="dto"></param>
  224. /// <returns></returns>
  225. public object ToOptimizedResult<T>(IRequest request, T dto)
  226. {
  227. return ToOptimizedResultInternal(request, dto);
  228. }
  229. private object ToOptimizedResultInternal<T>(IRequest request, T dto, IDictionary<string, string> responseHeaders = null)
  230. {
  231. // TODO: @bond use Span and .Equals
  232. var contentType = request.ResponseContentType?.Split(';')[0].Trim().ToLowerInvariant();
  233. switch (contentType)
  234. {
  235. case "application/xml":
  236. case "text/xml":
  237. case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
  238. return GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders);
  239. case "application/json":
  240. case "text/json":
  241. return GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders);
  242. default:
  243. break;
  244. }
  245. var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);
  246. var ms = new MemoryStream();
  247. var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
  248. writerFn(dto, ms);
  249. ms.Position = 0;
  250. if (isHeadRequest)
  251. {
  252. using (ms)
  253. {
  254. return GetHttpResult(request, Array.Empty<byte>(), contentType, true, responseHeaders);
  255. }
  256. }
  257. return GetHttpResult(request, ms, contentType, true, responseHeaders);
  258. }
  259. private IHasHeaders GetCompressedResult(byte[] content,
  260. string requestedCompressionType,
  261. IDictionary<string, string> responseHeaders,
  262. bool isHeadRequest,
  263. string contentType)
  264. {
  265. if (responseHeaders == null)
  266. {
  267. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  268. }
  269. content = Compress(content, requestedCompressionType);
  270. responseHeaders[HeaderNames.ContentEncoding] = requestedCompressionType;
  271. responseHeaders[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
  272. var contentLength = content.Length;
  273. if (isHeadRequest)
  274. {
  275. var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
  276. AddResponseHeaders(result, responseHeaders);
  277. return result;
  278. }
  279. else
  280. {
  281. var result = new StreamWriter(content, contentType, contentLength);
  282. AddResponseHeaders(result, responseHeaders);
  283. return result;
  284. }
  285. }
  286. private byte[] Compress(byte[] bytes, string compressionType)
  287. {
  288. if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
  289. {
  290. return Deflate(bytes);
  291. }
  292. if (string.Equals(compressionType, "gzip", StringComparison.OrdinalIgnoreCase))
  293. {
  294. return GZip(bytes);
  295. }
  296. throw new NotSupportedException(compressionType);
  297. }
  298. private static byte[] Deflate(byte[] bytes)
  299. {
  300. // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
  301. // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
  302. using (var ms = new MemoryStream())
  303. using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
  304. {
  305. zipStream.Write(bytes, 0, bytes.Length);
  306. zipStream.Dispose();
  307. return ms.ToArray();
  308. }
  309. }
  310. private static byte[] GZip(byte[] buffer)
  311. {
  312. using (var ms = new MemoryStream())
  313. using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
  314. {
  315. zipStream.Write(buffer, 0, buffer.Length);
  316. zipStream.Dispose();
  317. return ms.ToArray();
  318. }
  319. }
  320. private static string SerializeToXmlString(object from)
  321. {
  322. using (var ms = new MemoryStream())
  323. {
  324. var xwSettings = new XmlWriterSettings();
  325. xwSettings.Encoding = new UTF8Encoding(false);
  326. xwSettings.OmitXmlDeclaration = false;
  327. using (var xw = XmlWriter.Create(ms, xwSettings))
  328. {
  329. var serializer = new DataContractSerializer(from.GetType());
  330. serializer.WriteObject(xw, from);
  331. xw.Flush();
  332. ms.Seek(0, SeekOrigin.Begin);
  333. using (var reader = new StreamReader(ms))
  334. {
  335. return reader.ReadToEnd();
  336. }
  337. }
  338. }
  339. }
  340. /// <summary>
  341. /// Pres the process optimized result.
  342. /// </summary>
  343. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
  344. {
  345. bool noCache = (requestContext.Headers[HeaderNames.CacheControl].ToString()).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
  346. AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
  347. if (!noCache)
  348. {
  349. DateTime.TryParse(requestContext.Headers[HeaderNames.IfModifiedSince], out var ifModifiedSinceHeader);
  350. if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
  351. {
  352. AddAgeHeader(responseHeaders, options.DateLastModified);
  353. var result = new HttpResult(Array.Empty<byte>(), options.ContentType ?? "text/html", HttpStatusCode.NotModified);
  354. AddResponseHeaders(result, responseHeaders);
  355. return result;
  356. }
  357. }
  358. return null;
  359. }
  360. public Task<object> GetStaticFileResult(IRequest requestContext,
  361. string path,
  362. FileShareMode fileShare = FileShareMode.Read)
  363. {
  364. if (string.IsNullOrEmpty(path))
  365. {
  366. throw new ArgumentNullException(nameof(path));
  367. }
  368. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  369. {
  370. Path = path,
  371. FileShare = fileShare
  372. });
  373. }
  374. public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options)
  375. {
  376. var path = options.Path;
  377. var fileShare = options.FileShare;
  378. if (string.IsNullOrEmpty(path))
  379. {
  380. throw new ArgumentNullException(nameof(path));
  381. }
  382. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  383. {
  384. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  385. }
  386. if (string.IsNullOrEmpty(options.ContentType))
  387. {
  388. options.ContentType = MimeTypes.GetMimeType(path);
  389. }
  390. if (!options.DateLastModified.HasValue)
  391. {
  392. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  393. }
  394. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  395. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  396. return GetStaticResult(requestContext, options);
  397. }
  398. /// <summary>
  399. /// Gets the file stream.
  400. /// </summary>
  401. /// <param name="path">The path.</param>
  402. /// <param name="fileShare">The file share.</param>
  403. /// <returns>Stream.</returns>
  404. private Stream GetFileStream(string path, FileShareMode fileShare)
  405. {
  406. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  407. }
  408. public Task<object> GetStaticResult(IRequest requestContext,
  409. Guid cacheKey,
  410. DateTime? lastDateModified,
  411. TimeSpan? cacheDuration,
  412. string contentType,
  413. Func<Task<Stream>> factoryFn,
  414. IDictionary<string, string> responseHeaders = null,
  415. bool isHeadRequest = false)
  416. {
  417. return GetStaticResult(requestContext, new StaticResultOptions
  418. {
  419. CacheDuration = cacheDuration,
  420. ContentFactory = factoryFn,
  421. ContentType = contentType,
  422. DateLastModified = lastDateModified,
  423. IsHeadRequest = isHeadRequest,
  424. ResponseHeaders = responseHeaders
  425. });
  426. }
  427. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  428. {
  429. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  430. var contentType = options.ContentType;
  431. if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
  432. {
  433. // See if the result is already cached in the browser
  434. var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
  435. if (result != null)
  436. {
  437. return result;
  438. }
  439. }
  440. // TODO: We don't really need the option value
  441. var isHeadRequest = options.IsHeadRequest || string.Equals(requestContext.Verb, "HEAD", StringComparison.OrdinalIgnoreCase);
  442. var factoryFn = options.ContentFactory;
  443. var responseHeaders = options.ResponseHeaders;
  444. AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
  445. AddAgeHeader(responseHeaders, options.DateLastModified);
  446. var rangeHeader = requestContext.Headers[HeaderNames.Range];
  447. if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
  448. {
  449. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem, _streamHelper)
  450. {
  451. OnComplete = options.OnComplete,
  452. OnError = options.OnError,
  453. FileShare = options.FileShare
  454. };
  455. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  456. return hasHeaders;
  457. }
  458. var stream = await factoryFn().ConfigureAwait(false);
  459. var totalContentLength = options.ContentLength;
  460. if (!totalContentLength.HasValue)
  461. {
  462. try
  463. {
  464. totalContentLength = stream.Length;
  465. }
  466. catch (NotSupportedException)
  467. {
  468. }
  469. }
  470. if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
  471. {
  472. var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
  473. {
  474. OnComplete = options.OnComplete
  475. };
  476. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  477. return hasHeaders;
  478. }
  479. else
  480. {
  481. if (totalContentLength.HasValue)
  482. {
  483. responseHeaders["Content-Length"] = totalContentLength.Value.ToString(CultureInfo.InvariantCulture);
  484. }
  485. if (isHeadRequest)
  486. {
  487. using (stream)
  488. {
  489. return GetHttpResult(requestContext, Array.Empty<byte>(), contentType, true, responseHeaders);
  490. }
  491. }
  492. var hasHeaders = new StreamWriter(stream, contentType)
  493. {
  494. OnComplete = options.OnComplete,
  495. OnError = options.OnError
  496. };
  497. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  498. return hasHeaders;
  499. }
  500. }
  501. /// <summary>
  502. /// Adds the caching responseHeaders.
  503. /// </summary>
  504. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
  505. bool noCache, DateTime? lastModifiedDate)
  506. {
  507. if (noCache)
  508. {
  509. responseHeaders[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
  510. responseHeaders[HeaderNames.Pragma] = "no-cache, no-store, must-revalidate";
  511. return;
  512. }
  513. if (cacheDuration.HasValue)
  514. {
  515. responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
  516. }
  517. else
  518. {
  519. responseHeaders[HeaderNames.CacheControl] = "public";
  520. }
  521. if (lastModifiedDate.HasValue)
  522. {
  523. responseHeaders[HeaderNames.LastModified] = lastModifiedDate.Value.ToString(CultureInfo.InvariantCulture);
  524. }
  525. }
  526. /// <summary>
  527. /// Adds the age header.
  528. /// </summary>
  529. /// <param name="responseHeaders">The responseHeaders.</param>
  530. /// <param name="lastDateModified">The last date modified.</param>
  531. private static void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  532. {
  533. if (lastDateModified.HasValue)
  534. {
  535. responseHeaders[HeaderNames.Age] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  536. }
  537. }
  538. /// <summary>
  539. /// Determines whether [is not modified] [the specified if modified since].
  540. /// </summary>
  541. /// <param name="ifModifiedSince">If modified since.</param>
  542. /// <param name="cacheDuration">Duration of the cache.</param>
  543. /// <param name="dateModified">The date modified.</param>
  544. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  545. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  546. {
  547. if (dateModified.HasValue)
  548. {
  549. var lastModified = NormalizeDateForComparison(dateModified.Value);
  550. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  551. return lastModified <= ifModifiedSince;
  552. }
  553. if (cacheDuration.HasValue)
  554. {
  555. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  556. if (DateTime.UtcNow < cacheExpirationDate)
  557. {
  558. return true;
  559. }
  560. }
  561. return false;
  562. }
  563. /// <summary>
  564. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  565. /// </summary>
  566. /// <param name="date">The date.</param>
  567. /// <returns>DateTime.</returns>
  568. private static DateTime NormalizeDateForComparison(DateTime date)
  569. {
  570. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  571. }
  572. /// <summary>
  573. /// Adds the response headers.
  574. /// </summary>
  575. /// <param name="hasHeaders">The has options.</param>
  576. /// <param name="responseHeaders">The response headers.</param>
  577. private static void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  578. {
  579. foreach (var item in responseHeaders)
  580. {
  581. hasHeaders.Headers[item.Key] = item.Value;
  582. }
  583. }
  584. }
  585. }