HttpResultFactory.cs 26 KB

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