HttpResultFactory.cs 26 KB

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