private static void CopyHeadersToHttpListener(SerialisableResponse response, IHeaderCollection responseHeaders, string rebaseEndpoint) { if (response == null || response.Headers == null) { return; } response.Headers.Remove("Pragma"); response.Headers.Add("Server", new[] { string.Empty }); response.Headers.Remove("X-Powered-By"); foreach (var pair in response.Headers) { // Header filters: switch (pair.Key) { // Skip headers we MUST NOT change: case "Transfer-Encoding": // prevent mismatch of Chunked encoding from breaking things case "Content-Length": // we handle this one specially continue; // Filter out vanity headers: case "Pragma": case "Server": case "X-Powered-By": case "Via": continue; } if (pair.Key == "Location") { if (Uri.TryCreate(string.Join(",", pair.Value), UriKind.Absolute, out var redirectUrl)) { if (redirectUrl.Host == "0.0.0.0") // local redirect. Pass back the *external* url { var newTarget = rebaseEndpoint + redirectUrl.PathAndQuery; responseHeaders[pair.Key] = newTarget; continue; } } } if (responseHeaders[pair.Key] == null) { responseHeaders[pair.Key] = string.Join(",", pair.Value); } else { responseHeaders.Add(pair.Key, string.Join(", ", pair.Value)); } } }
/// <summary> /// Copy a serialisable response to a contextual response. /// Any redirect to a 0.0.0.0 IP will be replaced with the rebaseUrl /// </summary> public static void CopyToHttpListener(SerialisableResponse result, IResponse response, string rebaseUrl) { response.StatusCode = result.StatusCode; CopyHeadersToHttpListener(result, response.Headers, rebaseUrl); response.StatusDescription = result.StatusMessage; // output stream must be last if (result.Content != null) { response.OutputStream.Write(result.Content, 0, result.Content.Length); } }
/// <summary> /// Create a connection for a single serialised request /// </summary> public MemoryConnection(SerialisableRequest request) { _request = request; if (_request.Headers == null) { _request.Headers = new Dictionary <string, string>(); } _headersRead = false; Id = Guid.Empty; LocalIP = UnknownLocalIP; RemoteIP = UnknownRemoteIP; _resultBody = new MemoryStream(); _result = new SerialisableResponse { Headers = new Dictionary <string, string[]>(), StatusCode = 200, StatusMessage = DefaultStatusMessage }; }
/// <summary> /// Create a new context for an incoming serialisable request /// </summary> public SerialisableContext(SerialisableRequest request) { Request = new SerialisableRequestWrapper(request); Response = new SerialisableResponseWrapper(SerialisableResponse.CreateEmpty()); }
/// <summary> /// Wrap a response object /// </summary> public SerialisableResponseWrapper(SerialisableResponse targetResponse) { _response = targetResponse; _contentStream = new MemoryStream(); _headerWrapper = new DictionaryArrayHeaderWrapper(targetResponse.Headers); }