HttpResultFactory.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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"] = string.Format("\"{0}\"", 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. if (!options.DateLastModified.HasValue)
  283. {
  284. options.DateLastModified = _fileSystem.GetLastWriteTimeUtc(path);
  285. }
  286. var cacheKey = path + options.DateLastModified.Value.Ticks;
  287. options.CacheKey = cacheKey.GetMD5();
  288. options.ContentFactory = () => Task.FromResult(GetFileStream(path, fileShare));
  289. return GetStaticResult(requestContext, options);
  290. }
  291. /// <summary>
  292. /// Gets the file stream.
  293. /// </summary>
  294. /// <param name="path">The path.</param>
  295. /// <param name="fileShare">The file share.</param>
  296. /// <returns>Stream.</returns>
  297. private Stream GetFileStream(string path, FileShare fileShare)
  298. {
  299. return _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, fileShare);
  300. }
  301. public Task<object> GetStaticResult(IRequest requestContext,
  302. Guid cacheKey,
  303. DateTime? lastDateModified,
  304. TimeSpan? cacheDuration,
  305. string contentType,
  306. Func<Task<Stream>> factoryFn,
  307. IDictionary<string, string> responseHeaders = null,
  308. bool isHeadRequest = false)
  309. {
  310. return GetStaticResult(requestContext, new StaticResultOptions
  311. {
  312. CacheDuration = cacheDuration,
  313. CacheKey = cacheKey,
  314. ContentFactory = factoryFn,
  315. ContentType = contentType,
  316. DateLastModified = lastDateModified,
  317. IsHeadRequest = isHeadRequest,
  318. ResponseHeaders = responseHeaders
  319. });
  320. }
  321. public async Task<object> GetStaticResult(IRequest requestContext, StaticResultOptions options)
  322. {
  323. var cacheKey = options.CacheKey;
  324. options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  325. var contentType = options.ContentType;
  326. if (cacheKey == Guid.Empty)
  327. {
  328. throw new ArgumentNullException("cacheKey");
  329. }
  330. if (options.ContentFactory == null)
  331. {
  332. throw new ArgumentNullException("factoryFn");
  333. }
  334. var key = cacheKey.ToString("N");
  335. // See if the result is already cached in the browser
  336. var result = GetCachedResult(requestContext, options.ResponseHeaders, cacheKey, key, options.DateLastModified, options.CacheDuration, contentType);
  337. if (result != null)
  338. {
  339. return result;
  340. }
  341. var compress = ShouldCompressResponse(requestContext, contentType);
  342. var hasOptions = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false);
  343. AddResponseHeaders(hasOptions, options.ResponseHeaders);
  344. return hasOptions;
  345. }
  346. /// <summary>
  347. /// Shoulds the compress response.
  348. /// </summary>
  349. /// <param name="requestContext">The request context.</param>
  350. /// <param name="contentType">Type of the content.</param>
  351. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  352. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  353. {
  354. // It will take some work to support compression with byte range requests
  355. if (!string.IsNullOrEmpty(requestContext.GetHeader("Range")))
  356. {
  357. return false;
  358. }
  359. // Don't compress media
  360. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  361. {
  362. return false;
  363. }
  364. // Don't compress images
  365. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  366. {
  367. return false;
  368. }
  369. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  370. {
  371. return false;
  372. }
  373. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  374. {
  375. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  376. {
  377. return true;
  378. }
  379. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  380. {
  381. return true;
  382. }
  383. return false;
  384. }
  385. return true;
  386. }
  387. /// <summary>
  388. /// The us culture
  389. /// </summary>
  390. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  391. private async Task<IHasOptions> GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress)
  392. {
  393. var isHeadRequest = options.IsHeadRequest;
  394. var factoryFn = options.ContentFactory;
  395. var contentType = options.ContentType;
  396. var responseHeaders = options.ResponseHeaders;
  397. var requestedCompressionType = requestContext.GetCompressionType();
  398. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  399. {
  400. var rangeHeader = requestContext.GetHeader("Range");
  401. var stream = await factoryFn().ConfigureAwait(false);
  402. if (!string.IsNullOrEmpty(rangeHeader))
  403. {
  404. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger)
  405. {
  406. OnComplete = options.OnComplete
  407. };
  408. }
  409. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  410. if (isHeadRequest)
  411. {
  412. stream.Dispose();
  413. return GetHttpResult(new byte[] { }, contentType);
  414. }
  415. return new StreamWriter(stream, contentType, _logger)
  416. {
  417. OnComplete = options.OnComplete,
  418. OnError = options.OnError
  419. };
  420. }
  421. string content;
  422. using (var stream = await factoryFn().ConfigureAwait(false))
  423. {
  424. using (var reader = new StreamReader(stream))
  425. {
  426. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  427. }
  428. }
  429. var contents = content.Compress(requestedCompressionType);
  430. responseHeaders["Content-Length"] = contents.Length.ToString(UsCulture);
  431. if (isHeadRequest)
  432. {
  433. return GetHttpResult(new byte[] { }, contentType);
  434. }
  435. return new CompressedResult(contents, requestedCompressionType, contentType);
  436. }
  437. /// <summary>
  438. /// Adds the caching responseHeaders.
  439. /// </summary>
  440. /// <param name="responseHeaders">The responseHeaders.</param>
  441. /// <param name="cacheKey">The cache key.</param>
  442. /// <param name="lastDateModified">The last date modified.</param>
  443. /// <param name="cacheDuration">Duration of the cache.</param>
  444. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  445. {
  446. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  447. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  448. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  449. {
  450. AddAgeHeader(responseHeaders, lastDateModified);
  451. responseHeaders["LastModified"] = lastDateModified.Value.ToString("r");
  452. }
  453. if (cacheDuration.HasValue)
  454. {
  455. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  456. }
  457. else if (!string.IsNullOrEmpty(cacheKey))
  458. {
  459. responseHeaders["Cache-Control"] = "public";
  460. }
  461. else
  462. {
  463. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  464. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  465. }
  466. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  467. }
  468. /// <summary>
  469. /// Adds the expires header.
  470. /// </summary>
  471. /// <param name="responseHeaders">The responseHeaders.</param>
  472. /// <param name="cacheKey">The cache key.</param>
  473. /// <param name="cacheDuration">Duration of the cache.</param>
  474. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  475. {
  476. if (cacheDuration.HasValue)
  477. {
  478. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  479. }
  480. else if (string.IsNullOrEmpty(cacheKey))
  481. {
  482. responseHeaders["Expires"] = "-1";
  483. }
  484. }
  485. /// <summary>
  486. /// Adds the age header.
  487. /// </summary>
  488. /// <param name="responseHeaders">The responseHeaders.</param>
  489. /// <param name="lastDateModified">The last date modified.</param>
  490. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  491. {
  492. if (lastDateModified.HasValue)
  493. {
  494. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  495. }
  496. }
  497. /// <summary>
  498. /// Determines whether [is not modified] [the specified cache key].
  499. /// </summary>
  500. /// <param name="requestContext">The request context.</param>
  501. /// <param name="cacheKey">The cache key.</param>
  502. /// <param name="lastDateModified">The last date modified.</param>
  503. /// <param name="cacheDuration">Duration of the cache.</param>
  504. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  505. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  506. {
  507. var isNotModified = true;
  508. var ifModifiedSinceHeader = requestContext.GetHeader("If-Modified-Since");
  509. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  510. {
  511. DateTime ifModifiedSince;
  512. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  513. {
  514. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  515. }
  516. }
  517. var ifNoneMatchHeader = requestContext.GetHeader("If-None-Match");
  518. // Validate If-None-Match
  519. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  520. {
  521. Guid ifNoneMatch;
  522. if (Guid.TryParse(ifNoneMatchHeader ?? string.Empty, out ifNoneMatch))
  523. {
  524. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  525. {
  526. return true;
  527. }
  528. }
  529. }
  530. return false;
  531. }
  532. /// <summary>
  533. /// Determines whether [is not modified] [the specified if modified since].
  534. /// </summary>
  535. /// <param name="ifModifiedSince">If modified since.</param>
  536. /// <param name="cacheDuration">Duration of the cache.</param>
  537. /// <param name="dateModified">The date modified.</param>
  538. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  539. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  540. {
  541. if (dateModified.HasValue)
  542. {
  543. var lastModified = NormalizeDateForComparison(dateModified.Value);
  544. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  545. return lastModified <= ifModifiedSince;
  546. }
  547. if (cacheDuration.HasValue)
  548. {
  549. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  550. if (DateTime.UtcNow < cacheExpirationDate)
  551. {
  552. return true;
  553. }
  554. }
  555. return false;
  556. }
  557. /// <summary>
  558. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  559. /// </summary>
  560. /// <param name="date">The date.</param>
  561. /// <returns>DateTime.</returns>
  562. private DateTime NormalizeDateForComparison(DateTime date)
  563. {
  564. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  565. }
  566. /// <summary>
  567. /// Adds the response headers.
  568. /// </summary>
  569. /// <param name="hasOptions">The has options.</param>
  570. /// <param name="responseHeaders">The response headers.</param>
  571. private void AddResponseHeaders(IHasOptions hasOptions, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  572. {
  573. foreach (var item in responseHeaders)
  574. {
  575. hasOptions.Options[item.Key] = item.Value;
  576. }
  577. }
  578. /// <summary>
  579. /// Gets the error result.
  580. /// </summary>
  581. /// <param name="statusCode">The status code.</param>
  582. /// <param name="errorMessage">The error message.</param>
  583. /// <param name="responseHeaders">The response headers.</param>
  584. /// <returns>System.Object.</returns>
  585. public void ThrowError(int statusCode, string errorMessage, IDictionary<string, string> responseHeaders = null)
  586. {
  587. var error = new HttpError
  588. {
  589. Status = statusCode,
  590. ErrorCode = errorMessage
  591. };
  592. if (responseHeaders != null)
  593. {
  594. AddResponseHeaders(error, responseHeaders);
  595. }
  596. throw error;
  597. }
  598. public object GetAsyncStreamWriter(Func<Stream, Task> streamWriter, IDictionary<string, string> responseHeaders = null)
  599. {
  600. return new AsyncStreamWriterFunc(streamWriter, responseHeaders);
  601. }
  602. }
  603. }