| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.IO; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Net; |
| | | 6 | | using System.Text; |
| | | 7 | | |
| | | 8 | | namespace WireMock |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// The http listener request mapper. |
| | | 12 | | /// </summary> |
| | | 13 | | public class HttpListenerRequestMapper |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// The map. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="listenerRequest">The listener request.</param> |
| | | 19 | | /// <returns>The <see cref="RequestMessage"/>.</returns> |
| | | 20 | | public RequestMessage Map(HttpListenerRequest listenerRequest) |
| | 18 | 21 | | { |
| | 18 | 22 | | Uri url = listenerRequest.Url; |
| | 18 | 23 | | string verb = listenerRequest.HttpMethod; |
| | 18 | 24 | | byte[] body = GetRequestBody(listenerRequest); |
| | 18 | 25 | | Encoding bodyEncoding = body != null ? listenerRequest.ContentEncoding : null; |
| | 18 | 26 | | string bodyAsString = bodyEncoding?.GetString(body); |
| | 18 | 27 | | var listenerHeaders = listenerRequest.Headers; |
| | 100 | 28 | | var headers = listenerHeaders.AllKeys.ToDictionary(k => k, k => listenerHeaders[k]); |
| | 18 | 29 | | var cookies = new Dictionary<string, string>(); |
| | | 30 | | |
| | 54 | 31 | | foreach (Cookie cookie in listenerRequest.Cookies) |
| | 0 | 32 | | cookies.Add(cookie.Name, cookie.Value); |
| | | 33 | | |
| | 18 | 34 | | return new RequestMessage(url, verb, body, bodyAsString, bodyEncoding, headers, cookies) { DateTime = DateTi |
| | 18 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// The get request body. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="request">The request.</param> |
| | | 41 | | /// <returns>The <see cref="string"/>.</returns> |
| | | 42 | | private byte[] GetRequestBody(HttpListenerRequest request) |
| | 18 | 43 | | { |
| | 18 | 44 | | if (!request.HasEntityBody) |
| | 16 | 45 | | { |
| | 16 | 46 | | return null; |
| | | 47 | | } |
| | | 48 | | |
| | 2 | 49 | | using (var bodyStream = request.InputStream) |
| | 2 | 50 | | { |
| | 2 | 51 | | using (var memoryStream = new MemoryStream()) |
| | 2 | 52 | | { |
| | 2 | 53 | | bodyStream.CopyTo(memoryStream); |
| | | 54 | | |
| | 2 | 55 | | return memoryStream.ToArray(); |
| | | 56 | | } |
| | | 57 | | } |
| | 18 | 58 | | } |
| | | 59 | | } |
| | | 60 | | } |