HttpResultFactory.cs 25 KB

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