HttpResultFactory.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. // Otherwise wrap into an HttpResult
  210. var httpResult = new HttpResult(result, contentType ?? "text/html", HttpStatusCode.NotModified);
  211. AddResponseHeaders(httpResult, responseHeaders);
  212. return httpResult;
  213. }
  214. /// <summary>
  215. /// Pres the process optimized result.
  216. /// </summary>
  217. /// <param name="requestContext">The request context.</param>
  218. /// <param name="responseHeaders">The responseHeaders.</param>
  219. /// <param name="cacheKey">The cache key.</param>
  220. /// <param name="cacheKeyString">The cache key string.</param>
  221. /// <param name="lastDateModified">The last date modified.</param>
  222. /// <param name="cacheDuration">Duration of the cache.</param>
  223. /// <param name="contentType">Type of the content.</param>
  224. /// <returns>System.Object.</returns>
  225. private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, Guid cacheKey, string cacheKeyString, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType)
  226. {
  227. responseHeaders["ETag"] = cacheKeyString;
  228. if (IsNotModified(requestContext, cacheKey, lastDateModified, cacheDuration))
  229. {
  230. AddAgeHeader(responseHeaders, lastDateModified);
  231. AddExpiresHeader(responseHeaders, cacheKeyString, cacheDuration);
  232. var result = new HttpResult(new byte[] { }, contentType ?? "text/html", HttpStatusCode.NotModified);
  233. AddResponseHeaders(result, responseHeaders);
  234. return result;
  235. }
  236. AddCachingHeaders(responseHeaders, cacheKeyString, lastDateModified, cacheDuration);
  237. return null;
  238. }
  239. /// <summary>
  240. /// Gets the static file result.
  241. /// </summary>
  242. /// <param name="requestContext">The request context.</param>
  243. /// <param name="path">The path.</param>
  244. /// <param name="fileShare">The file share.</param>
  245. /// <param name="responseHeaders">The response headers.</param>
  246. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  247. /// <returns>System.Object.</returns>
  248. /// <exception cref="System.ArgumentNullException">path</exception>
  249. public object GetStaticFileResult(IRequest requestContext, string path, FileShare fileShare = FileShare.Read, IDictionary<string, string> responseHeaders = null, bool isHeadRequest = false)
  250. {
  251. if (string.IsNullOrEmpty(path))
  252. {
  253. throw new ArgumentNullException("path");
  254. }
  255. if (fileShare != FileShare.Read && fileShare != FileShare.ReadWrite)
  256. {
  257. throw new ArgumentException("FileShare must be either Read or ReadWrite");
  258. }
  259. var dateModified = _fileSystem.GetLastWriteTimeUtc(path);
  260. var cacheKey = path + dateModified.Ticks;
  261. return GetStaticResult(requestContext, cacheKey.GetMD5(), dateModified, null, MimeTypes.GetMimeType(path), () => Task.FromResult(GetFileStream(path, fileShare)), responseHeaders, isHeadRequest);
  262. }
  263. /// <summary>
  264. /// Gets the file stream.
  265. /// </summary>
  266. /// <param name="path">The path.</param>
  267. /// <param name="fileShare">The file share.</param>
  268. /// <returns>Stream.</returns>
  269. private Stream GetFileStream(string path, FileShare fileShare)
  270. {
  271. return _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, fileShare, true);
  272. }
  273. /// <summary>
  274. /// Gets the static result.
  275. /// </summary>
  276. /// <param name="requestContext">The request context.</param>
  277. /// <param name="cacheKey">The cache key.</param>
  278. /// <param name="lastDateModified">The last date modified.</param>
  279. /// <param name="cacheDuration">Duration of the cache.</param>
  280. /// <param name="contentType">Type of the content.</param>
  281. /// <param name="factoryFn">The factory fn.</param>
  282. /// <param name="responseHeaders">The response headers.</param>
  283. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  284. /// <returns>System.Object.</returns>
  285. /// <exception cref="System.ArgumentNullException">cacheKey
  286. /// or
  287. /// factoryFn</exception>
  288. public object GetStaticResult(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType, Func<Task<Stream>> factoryFn, IDictionary<string, string> responseHeaders = null, bool isHeadRequest = false)
  289. {
  290. if (cacheKey == Guid.Empty)
  291. {
  292. throw new ArgumentNullException("cacheKey");
  293. }
  294. if (factoryFn == null)
  295. {
  296. throw new ArgumentNullException("factoryFn");
  297. }
  298. var key = cacheKey.ToString("N");
  299. if (responseHeaders == null)
  300. {
  301. responseHeaders = new Dictionary<string, string>();
  302. }
  303. // See if the result is already cached in the browser
  304. var result = GetCachedResult(requestContext, responseHeaders, cacheKey, key, lastDateModified, cacheDuration, contentType);
  305. if (result != null)
  306. {
  307. return result;
  308. }
  309. var compress = ShouldCompressResponse(requestContext, contentType);
  310. var hasOptions = GetStaticResult(requestContext, responseHeaders, contentType, factoryFn, compress, isHeadRequest).Result;
  311. AddResponseHeaders(hasOptions, responseHeaders);
  312. return hasOptions;
  313. }
  314. /// <summary>
  315. /// Shoulds the compress response.
  316. /// </summary>
  317. /// <param name="requestContext">The request context.</param>
  318. /// <param name="contentType">Type of the content.</param>
  319. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  320. private bool ShouldCompressResponse(IRequest requestContext, string contentType)
  321. {
  322. // It will take some work to support compression with byte range requests
  323. if (!string.IsNullOrEmpty(requestContext.GetHeader("Range")))
  324. {
  325. return false;
  326. }
  327. // Don't compress media
  328. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  329. {
  330. return false;
  331. }
  332. // Don't compress images
  333. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  334. {
  335. return false;
  336. }
  337. if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  338. {
  339. return false;
  340. }
  341. if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase))
  342. {
  343. if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase))
  344. {
  345. return true;
  346. }
  347. if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase))
  348. {
  349. return true;
  350. }
  351. return false;
  352. }
  353. return true;
  354. }
  355. /// <summary>
  356. /// The us culture
  357. /// </summary>
  358. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  359. /// <summary>
  360. /// Gets the static result.
  361. /// </summary>
  362. /// <param name="requestContext">The request context.</param>
  363. /// <param name="responseHeaders">The response headers.</param>
  364. /// <param name="contentType">Type of the content.</param>
  365. /// <param name="factoryFn">The factory fn.</param>
  366. /// <param name="compress">if set to <c>true</c> [compress].</param>
  367. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  368. /// <returns>Task{IHasOptions}.</returns>
  369. private async Task<IHasOptions> GetStaticResult(IRequest requestContext, IDictionary<string, string> responseHeaders, string contentType, Func<Task<Stream>> factoryFn, bool compress, bool isHeadRequest)
  370. {
  371. var requestedCompressionType = requestContext.GetCompressionType();
  372. if (!compress || string.IsNullOrEmpty(requestedCompressionType))
  373. {
  374. var stream = await factoryFn().ConfigureAwait(false);
  375. var rangeHeader = requestContext.GetHeader("Range");
  376. if (!string.IsNullOrEmpty(rangeHeader))
  377. {
  378. return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest);
  379. }
  380. responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture);
  381. if (isHeadRequest)
  382. {
  383. return GetHttpResult(new byte[] { }, contentType);
  384. }
  385. return new StreamWriter(stream, contentType, _logger);
  386. }
  387. if (isHeadRequest)
  388. {
  389. return GetHttpResult(new byte[] { }, contentType);
  390. }
  391. string content;
  392. using (var stream = await factoryFn().ConfigureAwait(false))
  393. {
  394. using (var reader = new StreamReader(stream))
  395. {
  396. content = await reader.ReadToEndAsync().ConfigureAwait(false);
  397. }
  398. }
  399. if (!SupportsCompression)
  400. {
  401. return new HttpResult(content, contentType);
  402. }
  403. var contents = content.Compress(requestedCompressionType);
  404. return new CompressedResult(contents, requestedCompressionType, contentType);
  405. }
  406. /// <summary>
  407. /// Adds the caching responseHeaders.
  408. /// </summary>
  409. /// <param name="responseHeaders">The responseHeaders.</param>
  410. /// <param name="cacheKey">The cache key.</param>
  411. /// <param name="lastDateModified">The last date modified.</param>
  412. /// <param name="cacheDuration">Duration of the cache.</param>
  413. private void AddCachingHeaders(IDictionary<string, string> responseHeaders, string cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  414. {
  415. // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
  416. // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
  417. if (lastDateModified.HasValue && (string.IsNullOrEmpty(cacheKey) || cacheDuration.HasValue))
  418. {
  419. AddAgeHeader(responseHeaders, lastDateModified);
  420. responseHeaders["LastModified"] = lastDateModified.Value.ToString("r");
  421. }
  422. if (cacheDuration.HasValue)
  423. {
  424. responseHeaders["Cache-Control"] = "public, max-age=" + Convert.ToInt32(cacheDuration.Value.TotalSeconds);
  425. }
  426. else if (!string.IsNullOrEmpty(cacheKey))
  427. {
  428. responseHeaders["Cache-Control"] = "public";
  429. }
  430. else
  431. {
  432. responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
  433. responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
  434. }
  435. AddExpiresHeader(responseHeaders, cacheKey, cacheDuration);
  436. }
  437. /// <summary>
  438. /// Adds the expires header.
  439. /// </summary>
  440. /// <param name="responseHeaders">The responseHeaders.</param>
  441. /// <param name="cacheKey">The cache key.</param>
  442. /// <param name="cacheDuration">Duration of the cache.</param>
  443. private void AddExpiresHeader(IDictionary<string, string> responseHeaders, string cacheKey, TimeSpan? cacheDuration)
  444. {
  445. if (cacheDuration.HasValue)
  446. {
  447. responseHeaders["Expires"] = DateTime.UtcNow.Add(cacheDuration.Value).ToString("r");
  448. }
  449. else if (string.IsNullOrEmpty(cacheKey))
  450. {
  451. responseHeaders["Expires"] = "-1";
  452. }
  453. }
  454. /// <summary>
  455. /// Adds the age header.
  456. /// </summary>
  457. /// <param name="responseHeaders">The responseHeaders.</param>
  458. /// <param name="lastDateModified">The last date modified.</param>
  459. private void AddAgeHeader(IDictionary<string, string> responseHeaders, DateTime? lastDateModified)
  460. {
  461. if (lastDateModified.HasValue)
  462. {
  463. responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
  464. }
  465. }
  466. /// <summary>
  467. /// Determines whether [is not modified] [the specified cache key].
  468. /// </summary>
  469. /// <param name="requestContext">The request context.</param>
  470. /// <param name="cacheKey">The cache key.</param>
  471. /// <param name="lastDateModified">The last date modified.</param>
  472. /// <param name="cacheDuration">Duration of the cache.</param>
  473. /// <returns><c>true</c> if [is not modified] [the specified cache key]; otherwise, <c>false</c>.</returns>
  474. private bool IsNotModified(IRequest requestContext, Guid? cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration)
  475. {
  476. var isNotModified = true;
  477. var ifModifiedSinceHeader = requestContext.GetHeader("If-Modified-Since");
  478. if (!string.IsNullOrEmpty(ifModifiedSinceHeader))
  479. {
  480. DateTime ifModifiedSince;
  481. if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince))
  482. {
  483. isNotModified = IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified);
  484. }
  485. }
  486. var ifNoneMatchHeader = requestContext.GetHeader("If-None-Match");
  487. // Validate If-None-Match
  488. if (isNotModified && (cacheKey.HasValue || !string.IsNullOrEmpty(ifNoneMatchHeader)))
  489. {
  490. Guid ifNoneMatch;
  491. if (Guid.TryParse(ifNoneMatchHeader ?? string.Empty, out ifNoneMatch))
  492. {
  493. if (cacheKey.HasValue && cacheKey.Value == ifNoneMatch)
  494. {
  495. return true;
  496. }
  497. }
  498. }
  499. return false;
  500. }
  501. /// <summary>
  502. /// Determines whether [is not modified] [the specified if modified since].
  503. /// </summary>
  504. /// <param name="ifModifiedSince">If modified since.</param>
  505. /// <param name="cacheDuration">Duration of the cache.</param>
  506. /// <param name="dateModified">The date modified.</param>
  507. /// <returns><c>true</c> if [is not modified] [the specified if modified since]; otherwise, <c>false</c>.</returns>
  508. private bool IsNotModified(DateTime ifModifiedSince, TimeSpan? cacheDuration, DateTime? dateModified)
  509. {
  510. if (dateModified.HasValue)
  511. {
  512. var lastModified = NormalizeDateForComparison(dateModified.Value);
  513. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  514. return lastModified <= ifModifiedSince;
  515. }
  516. if (cacheDuration.HasValue)
  517. {
  518. var cacheExpirationDate = ifModifiedSince.Add(cacheDuration.Value);
  519. if (DateTime.UtcNow < cacheExpirationDate)
  520. {
  521. return true;
  522. }
  523. }
  524. return false;
  525. }
  526. /// <summary>
  527. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  528. /// </summary>
  529. /// <param name="date">The date.</param>
  530. /// <returns>DateTime.</returns>
  531. private DateTime NormalizeDateForComparison(DateTime date)
  532. {
  533. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  534. }
  535. /// <summary>
  536. /// Adds the response headers.
  537. /// </summary>
  538. /// <param name="hasOptions">The has options.</param>
  539. /// <param name="responseHeaders">The response headers.</param>
  540. private void AddResponseHeaders(IHasOptions hasOptions, IEnumerable<KeyValuePair<string, string>> responseHeaders)
  541. {
  542. foreach (var item in responseHeaders)
  543. {
  544. hasOptions.Options[item.Key] = item.Value;
  545. }
  546. }
  547. /// <summary>
  548. /// Gets the error result.
  549. /// </summary>
  550. /// <param name="statusCode">The status code.</param>
  551. /// <param name="errorMessage">The error message.</param>
  552. /// <param name="responseHeaders">The response headers.</param>
  553. /// <returns>System.Object.</returns>
  554. public void ThrowError(int statusCode, string errorMessage, IDictionary<string, string> responseHeaders = null)
  555. {
  556. var error = new HttpError
  557. {
  558. Status = statusCode,
  559. ErrorCode = errorMessage
  560. };
  561. if (responseHeaders != null)
  562. {
  563. AddResponseHeaders(error, responseHeaders);
  564. }
  565. throw error;
  566. }
  567. public object GetOptimizedSerializedResultUsingCache<T>(IRequest request, T result)
  568. where T : class
  569. {
  570. var json = _jsonSerializer.SerializeToString(result);
  571. var cacheKey = json.GetMD5();
  572. return GetOptimizedResultUsingCache(request, cacheKey, null, null, () => result);
  573. }
  574. }
  575. }