HttpResultFactory.cs 26 KB

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