| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Net.Http; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using WireMock.Util; |
| | | 7 | | |
| | | 8 | | namespace WireMock.Http |
| | | 9 | | { |
| | | 10 | | internal static class HttpResponseMessageHelper |
| | | 11 | | { |
| | | 12 | | public static async Task<ResponseMessage> Create(HttpResponseMessage httpResponseMessage, Uri requiredUri, Uri o |
| | 8 | 13 | | { |
| | 8 | 14 | | var responseMessage = new ResponseMessage { StatusCode = (int)httpResponseMessage.StatusCode }; |
| | | 15 | | |
| | | 16 | | // Set both content and response headers, replacing URLs in values |
| | 8 | 17 | | var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty<K |
| | 8 | 18 | | if (httpResponseMessage.Content != null) |
| | 8 | 19 | | { |
| | 8 | 20 | | var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); |
| | 8 | 21 | | IEnumerable<string> contentTypeHeader = null; |
| | 28 | 22 | | if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.O |
| | 3 | 23 | | { |
| | 7 | 24 | | contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentTy |
| | 3 | 25 | | } |
| | | 26 | | |
| | 8 | 27 | | var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault()); |
| | 8 | 28 | | responseMessage.Body = body.BodyAsString; |
| | 8 | 29 | | responseMessage.BodyAsJson = body.BodyAsJson; |
| | 8 | 30 | | responseMessage.BodyAsBytes = body.BodyAsBytes; |
| | 8 | 31 | | } |
| | | 32 | | |
| | 92 | 33 | | foreach (var header in headers) |
| | 34 | 34 | | { |
| | | 35 | | // If Location header contains absolute redirect URL, and base URL is one that we proxy to, |
| | | 36 | | // we need to replace it to original one. |
| | 34 | 37 | | if (string.Equals(header.Key, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase) |
| | 34 | 38 | | && Uri.TryCreate(header.Value.First(), UriKind.Absolute, out Uri absoluteLocationUri) |
| | 34 | 39 | | && string.Equals(absoluteLocationUri.Host, requiredUri.Host, StringComparison.OrdinalIgnoreCase)) |
| | 1 | 40 | | { |
| | 1 | 41 | | var replacedLocationUri = new Uri(originalUri, absoluteLocationUri.PathAndQuery); |
| | 1 | 42 | | responseMessage.AddHeader(header.Key, replacedLocationUri.ToString()); |
| | 1 | 43 | | } |
| | | 44 | | else |
| | 33 | 45 | | { |
| | 33 | 46 | | responseMessage.AddHeader(header.Key, header.Value.ToArray()); |
| | 33 | 47 | | } |
| | 34 | 48 | | } |
| | | 49 | | |
| | 8 | 50 | | return responseMessage; |
| | 8 | 51 | | } |
| | | 52 | | } |
| | | 53 | | } |