HttpResultFactory.cs 26 KB

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