HttpResultFactory.cs 26 KB

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