HttpResultFactory.cs 25 KB

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