HttpResultFactory.cs 26 KB

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