using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WireMock.Util; #if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; #endif namespace WireMock.Owin { /// /// OwinRequestMapper /// internal class OwinRequestMapper { /// /// MapAsync IOwinRequest to RequestMessage /// /// /// public async Task MapAsync( #if !USE_ASPNETCORE IOwinRequest request #else HttpRequest request #endif ) { #if !USE_ASPNETCORE var urldetails = UrlUtils.Parse(request.Uri, request.PathBase); string clientIP = request.RemoteIpAddress; #else var urldetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase); var connection = request.HttpContext.Connection; string clientIP = connection.RemoteIpAddress.IsIPv4MappedToIPv6 ? connection.RemoteIpAddress.MapToIPv4().ToString() : connection.RemoteIpAddress.ToString(); #endif string method = request.Method; Dictionary headers = null; if (request.Headers.Any()) { headers = new Dictionary(); foreach (var header in request.Headers) { headers.Add(header.Key, header.Value); } } IDictionary cookies = null; if (request.Cookies.Any()) { cookies = new Dictionary(); foreach (var cookie in request.Cookies) { cookies.Add(cookie.Key, cookie.Value); } } BodyData body = null; if (request.Body != null && ShouldParseBody(method)) { body = await BodyParser.Parse(request.Body, request.ContentType); } return new RequestMessage(urldetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.Now }; } private bool ShouldParseBody(string method) { /* HEAD - No defined body semantics. GET - No defined body semantics. PUT - Body supported. POST - Body supported. DELETE - No defined body semantics. TRACE - Body not supported. OPTIONS - Body supported but no semantics on usage (maybe in the future). CONNECT - No defined body semantics PATCH - Body supported. */ return new[] { "PUT", "POST", "OPTIONS", "PATCH" }.Contains(method.ToUpper()); } } }