HttpResultFactory.cs 26 KB

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