HttpResultFactory.cs 29 KB

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