2
0

HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Serialization;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Net;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using Emby.Server.Implementations.HttpServer;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Services;
  15. using ServiceStack;
  16. using IRequest = MediaBrowser.Model.Services.IRequest;
  17. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  18. using StreamWriter = Emby.Server.Implementations.HttpServer.StreamWriter;
  19. namespace MediaBrowser.Server.Implementations.HttpServer
  20. {
  21. /// <summary>
  22. /// Class HttpResultFactory
  23. /// </summary>
  24. public class HttpResultFactory : IHttpResultFactory
  25. {
  26. /// <summary>
  27. /// The _logger
  28. /// </summary>
  29. private readonly ILogger _logger;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IJsonSerializer _jsonSerializer;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
  34. /// </summary>
  35. /// <param name="logManager">The log manager.</param>
  36. /// <param name="fileSystem">The file system.</param>
  37. /// <param name="jsonSerializer">The json serializer.</param>
  38. public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  39. {
  40. _fileSystem = fileSystem;
  41. _jsonSerializer = jsonSerializer;
  42. _logger = logManager.GetLogger("HttpResultFactory");
  43. }
  44. /// <summary>
  45. /// Gets the result.
  46. /// </summary>
  47. /// <param name="content">The content.</param>
  48. /// <param name="contentType">Type of the content.</param>
  49. /// <param name="responseHeaders">The response headers.</param>
  50. /// <returns>System.Object.</returns>
  51. public object GetResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  52. {
  53. return GetHttpResult(content, contentType, responseHeaders);
  54. }
  55. /// <summary>
  56. /// Gets the HTTP result.
  57. /// </summary>
  58. /// <param name="content">The content.</param>
  59. /// <param name="contentType">Type of the content.</param>
  60. /// <param name="responseHeaders">The response headers.</param>
  61. /// <returns>IHasHeaders.</returns>
  62. private IHasHeaders GetHttpResult(object content, string contentType, IDictionary<string, string> responseHeaders = null)
  63. {
  64. IHasHeaders result;
  65. var stream = content as Stream;
  66. if (stream != null)
  67. {
  68. result = new StreamWriter(stream, contentType, _logger);
  69. }
  70. else
  71. {
  72. var bytes = content as byte[];
  73. if (bytes != null)
  74. {
  75. result = new StreamWriter(bytes, contentType, _logger);
  76. }
  77. else
  78. {
  79. var text = content as string;
  80. if (text != null)
  81. {
  82. result = new StreamWriter(Encoding.UTF8.GetBytes(text), contentType, _logger);
  83. }
  84. else
  85. {
  86. result = new HttpResult(content, contentType);
  87. }
  88. }
  89. }
  90. if (responseHeaders == null)
  91. {
  92. responseHeaders = new Dictionary<string, string>();
  93. }
  94. responseHeaders["Expires"] = "-1";
  95. AddResponseHeaders(result, responseHeaders);
  96. return result;
  97. }
  98. /// <summary>
  99. /// Gets the optimized result.
  100. /// </summary>
  101. /// <typeparam name="T"></typeparam>
  102. /// <param name="requestContext">The request context.</param>
  103. /// <param name="result">The result.</param>
  104. /// <param name="responseHeaders">The response headers.</param>
  105. /// <returns>System.Object.</returns>
  106. /// <exception cref="System.ArgumentNullException">result</exception>
  107. public object GetOptimizedResult<T>(IRequest requestContext, T result, IDictionary<string, string> responseHeaders = null)
  108. where T : class
  109. {
  110. return GetOptimizedResultInternal<T>(requestContext, result, true, responseHeaders);
  111. }
  112. private object GetOptimizedResultInternal<T>(IRequest requestContext, T result, bool addCachePrevention, IDictionary<string, string> responseHeaders = null)
  113. where T : class
  114. {
  115. if (result == null)
  116. {
  117. throw new ArgumentNullException("result");
  118. }
  119. var optimizedResult = requestContext.ToOptimizedResult(result);
  120. if (responseHeaders == null)
  121. {
  122. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  123. }
  124. if (addCachePrevention)
  125. {
  126. responseHeaders["Expires"] = "-1";
  127. }
  128. // Apply headers
  129. var hasHeaders = optimizedResult as IHasHeaders;
  130. if (hasHeaders != null)
  131. {
  132. AddResponseHeaders(hasHeaders, responseHeaders);
  133. }
  134. return optimizedResult;
  135. }
  136. /// <summary>
  137. /// Gets the optimized result using cache.
  138. /// </summary>
  139. /// <typeparam name="T"></typeparam>
  140. /// <param name="requestContext">The request context.</param>
  141. /// <param name="cacheKey">The cache key.</param>
  142. /// <param name="lastDateModified">The last date modified.</param>
  143. /// <param name="cacheDuration">Duration of the cache.</param>
  144. /// <param name="factoryFn">The factory fn.</param>
  145. /// <param name="responseHeaders">The response headers.</param>
  146. /// <returns>System.Object.</returns>
  147. /// <exception cref="System.ArgumentNullException">cacheKey
  148. /// or
  149. /// factoryFn</exception>
  150. public object GetOptimizedResultUsingCache<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, IDictionary<string, string> responseHeaders = null)
  151. where T : class
  152. {
  153. if (cacheKey == Guid.Empty)
  154. {
  155. throw new ArgumentNullException("cacheKey");
  156. }
  157. if (factoryFn == null)
  158. {
  159. throw new ArgumentNullException("factoryFn");
  160. }
  161. var key = cacheKey.ToString("N");
  162. if (responseHeaders == null)
  163. {
  164. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  165. }
  166. // See if the result is already cached in the browser
  167. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, null);
  168. if (result != null)
  169. {
  170. return result;
  171. }
  172. return GetOptimizedResultInternal(requestContext, factoryFn(), false, responseHeaders);
  173. }
  174. /// <summary>
  175. /// To the cached result.
  176. /// </summary>
  177. /// <typeparam name="T"></typeparam>
  178. /// <param name="requestContext">The request context.</param>
  179. /// <param name="cacheKey">The cache key.</param>
  180. /// <param name="lastDateModified">The last date modified.</param>
  181. /// <param name="cacheDuration">Duration of the cache.</param>
  182. /// <param name="factoryFn">The factory fn.</param>
  183. /// <param name="contentType">Type of the content.</param>
  184. /// <param name="responseHeaders">The response headers.</param>
  185. /// <returns>System.Object.</returns>
  186. /// <exception cref="System.ArgumentNullException">cacheKey</exception>
  187. public object GetCachedResult<T>(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, Func<T> factoryFn, string contentType, IDictionary<string, string> responseHeaders = null)
  188. where T : class
  189. {
  190. if (cacheKey == Guid.Empty)
  191. {
  192. throw new ArgumentNullException("cacheKey");
  193. }
  194. if (factoryFn == null)
  195. {
  196. throw new ArgumentNullException("factoryFn");
  197. }
  198. var key = cacheKey.ToString("N");
  199. if (responseHeaders == null)
  200. {
  201. responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  202. }
  203. // See if the result is already cached in the browser
  204. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  205. if (result != null)
  206. {
  207. return result;
  208. }
  209. result = factoryFn();
  210. // Apply caching headers
  211. var hasHeaders = result as IHasHeaders;
  212. if (hasHeaders != null)
  213. {
  214. AddResponseHeaders(hasHeaders, responseHeaders);
  215. return hasHeaders;
  216. }
  217. IHasHeaders httpResult;
  218. var stream = result as Stream;
  219. if (stream != null)
  220. {
  221. httpResult = new StreamWriter(stream, contentType, _logger);
  222. }
  223. else
  224. {
  225. // Otherwise wrap into an HttpResult
  226. httpResult = new HttpResult(result, contentType ?? "text/html", HttpStatusCode.NotModified);
  227. }
  228. AddResponseHeaders(httpResult, responseHeaders);
  229. return httpResult;
  230. }
  231. /// <summary>
  232. /// Pres the process optimized result.
  233. /// </summary>
  234. /// <param name="requestContext">The request context.</param>
  235. /// <param name="responseHeaders">The responseHeaders.</param>
  236. /// <param name="cacheKey">The cache key.</param>
  237. /// <param name="cacheKeyString">The cache key string.</param>
  238. /// <param name="lastDateModified">The last date modified.</param>
  239. /// <param name="cacheDuration">Duration of the cache.</param>
  240. /// <param name="contentType">Type of the content.</param>
  241. /// <returns>System.Object.</returns>
  242. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  243. {
  244. responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString);
  245. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  246. {
  247. AddAgeHeader(responseHeaders, lastDateModified);
  248. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  249. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  250. AddResponseHeaders(result, responseHeaders);
  251. return result;
  252. }
  253. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  254. return null;
  255. }
  256. public Task<object> GetStaticFileResult(IRequest requestContext,
  257. string path,
  258. FileShareMode fileShare = FileShareMode.Read)
  259. {
  260. if (string.IsNullOrEmpty(path))
  261. {
  262. throw new ArgumentNullException("path");
  263. }
  264. return GetStaticFileResult(requestContext, new StaticFileResultOptions
  265. {
  266. Path = path,
  267. FileShare = fileShare
  268. });
  269. }
  270. public Task<object> GetStaticFileResult(IRequest requestContext,
  271. StaticFileResultOptions options)
  272. {
  273. var path = options.Path;
  274. var fileShare = options.FileShare;
  275. if (string.IsNullOrEmpty(path))
  276. {
  277. throw new ArgumentNullException("path");
  278. }
  279. if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite)
  280. {
  281. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  282. }
  283. if (string.IsNullOrWhiteSpace(options.ContentType))
  284. {
  285. options.ContentType = MimeTypes.GetMimeType(path);
  286. }
  287. if (!options.DateLastModified.HasValue)
  288. {
  289. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  290. }
  291. var cacheKey = path + options.DateLastModified.Value.Ticks;
  292. options.CacheKey = cacheKey.GetMD5();
  293. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  294. return GetStaticResult(requestContext, options);
  295. }
  296. /// <summary>
  297. /// Gets the file stream.
  298. /// </summary>
  299. /// <param name="path">The path.</param>
  300. /// <param name="fileShare">The file share.</param>
  301. /// <returns>Stream.</returns>
  302. private Stream GetFileStream(string path, FileShareMode fileShare)
  303. {
  304. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  305. }
  306. public Task<object> GetStaticResult(IRequest requestContext,
  307. Guid cacheKey,
  308. DateTime? lastDateModified,
  309. TimeSpan? cacheDuration,
  310. string contentType,
  311. Func<Task<Stream>> factoryFn,
  312. IDictionary<string, string> responseHeaders = null,
  313. bool isHeadRequest = false)
  314. {
  315. return GetStaticResult(requestContext, new StaticResultOptions
  316. {
  317. CacheDuration = cacheDuration,
  318. CacheKey = cacheKey,
  319. ContentFactory = factoryFn,
  320. ContentType = contentType,
  321. DateLastModified = lastDateModified,
  322. IsHeadRequest = isHeadRequest,
  323. ResponseHeaders = responseHeaders
  324. });
  325. }
  326. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  327. {
  328. var cacheKey = options.CacheKey;
  329. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  330. var contentType = options.ContentType;
  331. if (cacheKey == Guid.Empty)
  332. {
  333. throw new ArgumentNullException("cacheKey");
  334. }
  335. if (options.ContentFactory == null)
  336. {
  337. throw new ArgumentNullException("factoryFn");
  338. }
  339. var key = cacheKey.ToString("N");
  340. // See if the result is already cached in the browser
  341. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  342. if (result != null)
  343. {
  344. return result;
  345. }
  346. var compress = ShouldCompressResponse(requestContext, contentType);
  347. var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  348. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  349. return hasHeaders;
  350. }
  351. /// <summary>
  352. /// Shoulds the compress response.
  353. /// </summary>
  354. /// <param name="requestContext">The request context.</param>
  355. /// <param name="contentType">Type of the content.</param>
  356. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  357. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  358. {
  359. // It will take some work to support compression with byte range requests
  360. if (!string.IsNullOrEmpty(requestContext.GetHeader("Range")))
  361. {
  362. return false;
  363. }
  364. // Don't compress media
  365. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  366. {
  367. return false;
  368. }
  369. // Don't compress images
  370. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  371. {
  372. return false;
  373. }
  374. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  375. {
  376. return false;
  377. }
  378. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  379. {
  380. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  381. {
  382. return true;
  383. }
  384. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  385. {
  386. return true;
  387. }
  388. return false;
  389. }
  390. return true;
  391. }
  392. /// <summary>
  393. /// The us culture
  394. /// </summary>
  395. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  396. private async Task<IHasHeaders> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  397. {
  398. var isHeadRequest = options.IsHeadRequest;
  399. var factoryFn = options.ContentFactory;
  400. var contentType = options.ContentType;
  401. var responseHeaders = options.ResponseHeaders;
  402. var requestedCompressionType = requestContext.GetCompressionType();
  403. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  404. {
  405. var rangeHeader = requestContext.GetHeader("Range");
  406. var stream = await factoryFn().ConfigureAwait(false);
  407. if (!string.IsNullOrEmpty(rangeHeader))
  408. {
  409. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  410. {
  411. OnComplete = options.OnComplete
  412. };
  413. }
  414. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  415. if (isHeadRequest)
  416. {
  417. stream.Dispose();
  418. return GetHttpResult(new byte[] { }, contentType);
  419. }
  420. return new StreamWriter(stream, contentType, _logger)
  421. {
  422. OnComplete = options.OnComplete,
  423. OnError = options.OnError
  424. };
  425. }
  426. string content;
  427. using (var stream = await factoryFn().ConfigureAwait(false))
  428. {
  429. using (var reader = new StreamReader(stream))
  430. {
  431. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  432. }
  433. }
  434. var contents = content.Compress(requestedCompressionType);
  435. responseHeaders["Content-Length"] = contents.Length.ToString(UsCulture);
  436. if (isHeadRequest)
  437. {
  438. return GetHttpResult(new byte[] { }, contentType);
  439. }
  440. return new CompressedResult(contents, requestedCompressionType, contentType);
  441. }
  442. /// <summary>
  443. /// Adds the caching responseHeaders.
  444. /// </summary>
  445. /// <param name="responseHeaders">The responseHeaders.</param>
  446. /// <param name="cacheKey">The cache key.</param>
  447. /// <param name="lastDateModified">The last date modified.</param>
  448. /// <param name="cacheDuration">Duration of the cache.</param>
  449. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  450. {
  451. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  452. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  453. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  454. {
  455. AddAgeHeader(responseHeaders, lastDateModified);
  456. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  457. }
  458. if (cacheDuration.HasValue)
  459. {
  460. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  461. }
  462. else if (!string.IsNullOrEmpty(cacheKey))
  463. {
  464. responseHeaders["Cache-Control"] = "public";
  465. }
  466. else
  467. {
  468. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  469. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  470. }
  471. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  472. }
  473. /// <summary>
  474. /// Adds the expires header.
  475. /// </summary>
  476. /// <param name="responseHeaders">The responseHeaders.</param>
  477. /// <param name="cacheKey">The cache key.</param>
  478. /// <param name="cacheDuration">Duration of the cache.</param>
  479. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  480. {
  481. if (cacheDuration.HasValue)
  482. {
  483. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  484. }
  485. else if (string.IsNullOrEmpty(cacheKey))
  486. {
  487. responseHeaders["Expires"] = "-1";
  488. }
  489. }
  490. /// <summary>
  491. /// Adds the age header.
  492. /// </summary>
  493. /// <param name="responseHeaders">The responseHeaders.</param>
  494. /// <param name="lastDateModified">The last date modified.</param>
  495. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  496. {
  497. if (lastDateModified.HasValue)
  498. {
  499. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  500. }
  501. }
  502. /// <summary>
  503. /// Determines whether [is not modified] [the specified cache key].
  504. /// </summary>
  505. /// <param name="requestContext">The request context.</param>
  506. /// <param name="cacheKey">The cache key.</param>
  507. /// <param name="lastDateModified">The last date modified.</param>
  508. /// <param name="cacheDuration">Duration of the cache.</param>
  509. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  510. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  511. {
  512. var isNotModified = true;
  513. var ifModifiedSinceHeader = requestContext.GetHeader("If-Modified-Since");
  514. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  515. {
  516. DateTime ifModifiedSince;
  517. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  518. {
  519. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  520. }
  521. }
  522. var ifNoneMatchHeader = requestContext.GetHeader("If-None-Match");
  523. // Validate If-None-Match
  524. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  525. {
  526. Guid ifNoneMatch;
  527. if (Guid.TryParse(ifNoneMatchHeader ?? string.Empty, out ifNoneMatch))
  528. {
  529. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  530. {
  531. return true;
  532. }
  533. }
  534. }
  535. return false;
  536. }
  537. /// <summary>
  538. /// Determines whether [is not modified] [the specified if modified since].
  539. /// </summary>
  540. /// <param name="ifModifiedSince">If modified since.</param>
  541. /// <param name="cacheDuration">Duration of the cache.</param>
  542. /// <param name="dateModified">The date modified.</param>
  543. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  544. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  545. {
  546. if (dateModified.HasValue)
  547. {
  548. var lastModified = NormalizeDateForComparison(dateModified.Value);
  549. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  550. return lastModified <= ifModifiedSince;
  551. }
  552. if (cacheDuration.HasValue)
  553. {
  554. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  555. if (DateTime.UtcNow < cacheExpirationDate)
  556. {
  557. return true;
  558. }
  559. }
  560. return false;
  561. }
  562. /// <summary>
  563. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  564. /// </summary>
  565. /// <param name="date">The date.</param>
  566. /// <returns>DateTime.</returns>
  567. private DateTime NormalizeDateForComparison(DateTime date)
  568. {
  569. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  570. }
  571. /// <summary>
  572. /// Adds the response headers.
  573. /// </summary>
  574. /// <param name="hasHeaders">The has options.</param>
  575. /// <param name="responseHeaders">The response headers.</param>
  576. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  577. {
  578. foreach (var item in responseHeaders)
  579. {
  580. hasHeaders.Headers[item.Key] = item.Value;
  581. }
  582. }
  583. }
  584. }