HttpResultFactory.cs 25 KB

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