HttpResultFactory.cs 26 KB

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