HttpResultFactory.cs 26 KB

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