HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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, noCache);
  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, noCache);
  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. // Quotes are valid in linux. They'll possibly cause issues here
  356. var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty);
  357. if (!string.IsNullOrWhiteSpace(filename))
  358. {
  359. options.ResponseHeaders["Content-Disposition"] = "inline; filename=\"" + filename + "\"";
  360. }
  361. return GetStaticResult(requestContext, options);
  362. }
  363. /// <summary>
  364. /// Gets the file stream.
  365. /// </summary>
  366. /// <param name="path">The path.</param>
  367. /// <param name="fileShare">The file share.</param>
  368. /// <returns>Stream.</returns>
  369. private Stream GetFileStream(string path, FileShareMode fileShare)
  370. {
  371. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShare);
  372. }
  373. public Task<object> GetStaticResult(IRequest requestContext,
  374. Guid cacheKey,
  375. DateTime? lastDateModified,
  376. TimeSpan? cacheDuration,
  377. string contentType,
  378. Func<Task<Stream>> factoryFn,
  379. IDictionary<string, string> responseHeaders = null,
  380. bool isHeadRequest = false)
  381. {
  382. return GetStaticResult(requestContext, new StaticResultOptions
  383. {
  384. CacheDuration = cacheDuration,
  385. CacheKey = cacheKey,
  386. ContentFactory = factoryFn,
  387. ContentType = contentType,
  388. DateLastModified = lastDateModified,
  389. IsHeadRequest = isHeadRequest,
  390. ResponseHeaders = responseHeaders
  391. });
  392. }
  393. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  394. {
  395. var cacheKey = options.CacheKey;
  396. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  397. var contentType = options.ContentType;
  398. if (cacheKey == Guid.Empty)
  399. {
  400. throw new ArgumentNullException("cacheKey");
  401. }
  402. var key = cacheKey.ToString("N");
  403. // See if the result is already cached in the browser
  404. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  405. if (result != null)
  406. {
  407. return result;
  408. }
  409. var isHeadRequest = options.IsHeadRequest;
  410. var factoryFn = options.ContentFactory;
  411. var responseHeaders = options.ResponseHeaders;
  412. //var requestedCompressionType = GetCompressionType(requestContext);
  413. var rangeHeader = requestContext.Headers.Get("Range");
  414. if (!isHeadRequest && !string.IsNullOrWhiteSpace(options.Path))
  415. {
  416. var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
  417. {
  418. OnComplete = options.OnComplete,
  419. OnError = options.OnError,
  420. FileShare = options.FileShare
  421. };
  422. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  423. return hasHeaders;
  424. }
  425. if (!string.IsNullOrWhiteSpace(rangeHeader))
  426. {
  427. var stream = await factoryFn().ConfigureAwait(false);
  428. var hasHeaders = new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  429. {
  430. OnComplete = options.OnComplete
  431. };
  432. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  433. return hasHeaders;
  434. }
  435. else
  436. {
  437. var stream = await factoryFn().ConfigureAwait(false);
  438. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  439. if (isHeadRequest)
  440. {
  441. stream.Dispose();
  442. return GetHttpResult(new byte[] { }, contentType, true);
  443. }
  444. var hasHeaders = new StreamWriter(stream, contentType, _logger)
  445. {
  446. OnComplete = options.OnComplete,
  447. OnError = options.OnError
  448. };
  449. AddResponseHeaders(hasHeaders, options.ResponseHeaders);
  450. return hasHeaders;
  451. }
  452. }
  453. /// <summary>
  454. /// The us culture
  455. /// </summary>
  456. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  457. /// <summary>
  458. /// Adds the caching responseHeaders.
  459. /// </summary>
  460. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, bool noCache)
  461. {
  462. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  463. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  464. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  465. {
  466. AddAgeHeader(responseHeaders, lastDateModified);
  467. responseHeaders["Last-Modified"] = lastDateModified.Value.ToString("r");
  468. }
  469. if (!noCache && cacheDuration.HasValue)
  470. {
  471. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  472. }
  473. else if (!noCache && !string.IsNullOrEmpty(cacheKey))
  474. {
  475. responseHeaders["Cache-Control"] = "public";
  476. }
  477. else
  478. {
  479. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  480. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  481. }
  482. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration, noCache);
  483. }
  484. /// <summary>
  485. /// Adds the expires header.
  486. /// </summary>
  487. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration, bool noCache)
  488. {
  489. if (!noCache && cacheDuration.HasValue)
  490. {
  491. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  492. }
  493. else if (string.IsNullOrEmpty(cacheKey))
  494. {
  495. responseHeaders["Expires"] = "-1";
  496. }
  497. }
  498. /// <summary>
  499. /// Adds the age header.
  500. /// </summary>
  501. /// <param name="responseHeaders">The responseHeaders.</param>
  502. /// <param name="lastDateModified">The last date modified.</param>
  503. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  504. {
  505. if (lastDateModified.HasValue)
  506. {
  507. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  508. }
  509. }
  510. /// <summary>
  511. /// Determines whether [is not modified] [the specified cache key].
  512. /// </summary>
  513. /// <param name="requestContext">The request context.</param>
  514. /// <param name="cacheKey">The cache key.</param>
  515. /// <param name="lastDateModified">The last date modified.</param>
  516. /// <param name="cacheDuration">Duration of the cache.</param>
  517. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  518. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  519. {
  520. //var isNotModified = true;
  521. var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since");
  522. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  523. {
  524. DateTime ifModifiedSince;
  525. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  526. {
  527. if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  528. {
  529. return true;
  530. }
  531. }
  532. }
  533. var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match");
  534. // Validate If-None-Match
  535. if ((cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  536. {
  537. Guid ifNoneMatch;
  538. ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"');
  539. if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch))
  540. {
  541. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  542. {
  543. return true;
  544. }
  545. }
  546. }
  547. return false;
  548. }
  549. /// <summary>
  550. /// Determines whether [is not modified] [the specified if modified since].
  551. /// </summary>
  552. /// <param name="ifModifiedSince">If modified since.</param>
  553. /// <param name="cacheDuration">Duration of the cache.</param>
  554. /// <param name="dateModified">The date modified.</param>
  555. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  556. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  557. {
  558. if (dateModified.HasValue)
  559. {
  560. var lastModified = NormalizeDateForComparison(dateModified.Value);
  561. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  562. return lastModified <= ifModifiedSince;
  563. }
  564. if (cacheDuration.HasValue)
  565. {
  566. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  567. if (DateTime.UtcNow < cacheExpirationDate)
  568. {
  569. return true;
  570. }
  571. }
  572. return false;
  573. }
  574. /// <summary>
  575. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  576. /// </summary>
  577. /// <param name="date">The date.</param>
  578. /// <returns>DateTime.</returns>
  579. private DateTime NormalizeDateForComparison(DateTime date)
  580. {
  581. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  582. }
  583. /// <summary>
  584. /// Adds the response headers.
  585. /// </summary>
  586. /// <param name="hasHeaders">The has options.</param>
  587. /// <param name="responseHeaders">The response headers.</param>
  588. private void AddResponseHeaders(IHasHeaders hasHeaders, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  589. {
  590. foreach (var item in responseHeaders)
  591. {
  592. hasHeaders.Headers[item.Key] = item.Value;
  593. }
  594. }
  595. }
  596. }