HttpResultFactory.cs 27 KB

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