private static string GetHttpRequestHeader(HttpHeaders headers, string headerName) { if (!headers.Contains(headerName)) return string.Empty; return headers.GetValues(headerName) .SingleOrDefault(); }
public void TestMultilineParse() { // // multiline values are acceptable if the next // line starts with spaces // string header = @"HeaderName: Some multiline value"; HttpHeaders headers = new HttpHeaders (); headers.Parse (new StringReader (header)); Assert.AreEqual ("Some multiline value", headers ["HeaderName"], "a1"); header = @"HeaderName: Some multiline value that spans a bunch of lines"; headers = new HttpHeaders (); headers.Parse (new StringReader (header)); Assert.AreEqual ("Some multiline value that spans a bunch of lines", headers ["HeaderName"], "a2"); }
public RequestHeaderMap(HttpHeaders headers) { this.headersCollection = headers.ToDictionary( x => x.Key.ToLower().Replace("-", string.Empty), x => string.Join(",", x.Value) ); }
protected Dictionary<string, string> ConvertToHeaders(string name, HttpHeaders headers) { var result = headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault()); result.Add("Host", GetHost(name)); return result; }
public async Task<IActionResult> ServerSniffer(string uri) { var request_headers = new Dictionary<string, string>(); var response_headers = new Dictionary<string, string>(); var http_headers = new HttpHeaders(); http_headers.RequestHeaders = request_headers; http_headers.ResponseHeaders = response_headers; using (var http_client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Head, uri); using (var response = await http_client.SendAsync(request)) { foreach (var header in response.Headers) { response_headers.Add(header.Key, string.Join(",", header.Value)); } foreach (var header in request.Headers) { request_headers.Add(header.Key, string.Join(",", header.Value)); } } } var json_result = new JsonResult(http_headers); return json_result; }
private static async Task<bool> AuthorizeUser(HttpHeaders headers) { HttpContext.Current.User = await GetClaimsForRoleAsync(headers) .ConfigureAwait(continueOnCapturedContext: false); return HttpContext.Current.User.Identity.IsAuthenticated; }
private static async Task<ClaimsPrincipal> GetClaimsForRoleAsync(HttpHeaders role) { return await Task.Run(() => new ClaimsPrincipal(new List<ClaimsIdentity> { new ClaimsIdentity("SecureAuth", "SafeType", role.GetValues("RoleType").FirstOrDefault()) })); }
public DummyProxy(string fakeEncoding) : base(new HttpSocket(new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))) { ResponseHeaders = new HttpHeaders(); ResponseHeaders.ContentEncoding = fakeEncoding; }
public void Getting_nonexistent_header_returns_default() { var headers = new HttpHeaders(); var nonexistent = headers.GetFirst<string>("nope"); nonexistent.ShouldBeNull(); }
// Copy constructor public DefaultHttpRequest(IHttpRequest existingRequest, Uri overrideUri = null) { this.body = existingRequest.Body; this.bodyContentType = existingRequest.BodyContentType; this.headers = new HttpHeaders(existingRequest.Headers); this.method = existingRequest.Method.Clone(); this.canonicalUri = new CanonicalUri(existingRequest.CanonicalUri, overrideResourcePath: overrideUri); }
public DefaultResourceDataRequest(ResourceAction action, Type resourceType, CanonicalUri uri, HttpHeaders requestHeaders, Map properties, bool skipCache) { this.action = action; this.uri = uri; this.requestHeaders = requestHeaders; this.resourceType = resourceType; this.properties = properties; this.skipCache = skipCache; }
public DefaultHttpResponse(int httpStatus, string responsePhrase, HttpHeaders headers, string body, string bodyContentType, bool transportError) { this.statusCode = httpStatus; this.responsePhrase = responsePhrase; this.headers = headers; this.body = body; this.bodyContentType = bodyContentType; this.transportError = transportError; }
/// <summary> /// Creates a new instance of <see cref="WebClientHttpResponse"/> /// with the given <see cref="HttpWebResponse"/> instance. /// </summary> /// <param name="response">The <see cref="HttpWebResponse"/> instance to use.</param> public WebClientHttpResponse(HttpWebResponse response) { ArgumentUtils.AssertNotNull(response, "response"); this.httpWebResponse = response; this.headers = new HttpHeaders(); this.Initialize(); }
public WebRequestorResponse(Stream stream, HttpStatusCode httpStatusCode, HttpHeaders headers, string contentType) { ContentType = contentType; Stream = stream; HttpStatusCode = httpStatusCode; if (headers != null) { Headers = headers.ToDictionary(i => i.Key, i => string.Join(";", i.Value)); } }
private static string GetHeaderString(HttpHeaders headers, string name) { IEnumerable<string> values; if (headers.TryGetValues(name, out values)) { return values.FirstOrDefault(); } return null; }
private static IDictionary<string, string> MapResponseHeaders(HttpHeaders headerCollection) { var resultHeaders = new Dictionary<string, string>(); foreach (var header in headerCollection) { resultHeaders.Add(header.Key, string.Join(",", header.Value)); } return resultHeaders; }
public ODataMessageWrapper(Stream stream, HttpHeaders headers) { _stream = stream; if (headers != null) { _headers = headers.ToDictionary(kvp => kvp.Key, kvp => String.Join(";", kvp.Value)); } else { _headers = new Dictionary<string, string>(); } }
public static void AddHeaders(HttpHeaders httpHeaders, JObject jheaders) { foreach (var keyValuePair in httpHeaders) { if (keyValuePair.Value.Count() > 1) { var separator = _SpaceDelimitedHeaders.Contains(keyValuePair.Key) ? " " : ", "; jheaders.Add(new JProperty(keyValuePair.Key, string.Join(separator, keyValuePair.Value))); } else jheaders.Add(new JProperty(keyValuePair.Key, keyValuePair.Value.First())); } }
/// <summary> /// Helper method to turn <see cref="HttpHeaders"/> into a regular dictionary /// </summary> /// <param name="h">The headers to extract</param> protected void ExtractHeaders(HttpHeaders h) { var dict = new Dictionary<string, string>(); foreach (var i in h.ToList()) { if (i.Value != null) { string header = i.Value.Aggregate(string.Empty, (current, j) => current + (j + " ")); dict.Add(i.Key, header); } } Headers = dict; }
private static EndpointStatus DetermineEndpointStatus(HttpHeaders headers) { var statusHeader = GetHeaderString(headers, typeof(EndpointStatus).Name); EndpointStatus status; if (Enum.TryParse(statusHeader, out status)) { return status; } // If no header or multiple entries present, assume endpoint is deprecated return EndpointStatus.Deprecated; }
internal static void MergeWebHeaderCollectionWithHttpHeaders(WebHeaderCollection headersToMerge, HttpHeaders mainHeaders, HttpHeaders contentHeaders) { foreach (string headerKey in headersToMerge.AllKeys) { if (WellKnownContentHeaders.Contains(headerKey)) { contentHeaders.TryAddWithoutValidation(headerKey, headersToMerge[headerKey]); } else { mainHeaders.TryAddWithoutValidation(headerKey, headersToMerge[headerKey]); } } }
public static void AddHeaders(HttpHeaders httpHeaders, JObject jheaders) { foreach (var header in httpHeaders) { if (header.Value.Count() > 1) { string delimiter = _SpaceDelimitedHeaders.Contains(header.Key) ? " " : ", "; jheaders.Add(new JProperty(header.Key, string.Join(delimiter, header.Value))); } else { jheaders.Add(new JProperty(header.Key, header.Value.First())); } } }
public GivenAnHttpHeaders() { Span<byte> headers; var bytes = new UTF8Encoding().GetBytes(HeadersString); unsafe { fixed (byte* buffer = bytes) { headers = new Span<byte>(buffer, bytes.Length); } } _httpHeaders = new HttpHeaders(headers); }
void DebugPrintHeaders(HttpHeaders headers) { foreach (var h in headers) { Debug.WriteLine("{0}: ", h.Key); int itemsPrintedSoFar = 0; foreach (var v in h.Value) { if (itemsPrintedSoFar != 0) Debug.Write(","); Debug.Write("{0}", v); itemsPrintedSoFar++; } } }
public HttpHeadersInjectAdapter(HttpHeaders headers) { _headers = headers ?? throw new ArgumentNullException(nameof(headers)); }
private static IDictionary <string, string> HttpHeadersToStringDictionary(HttpHeaders headers) { return(headers.ToDictionary((h1) => h1.Key, (h2) => string.Join(",", h2.Value))); }
internal static HttpResponseMessage ParseAsHttpResponse(string content) { var response = new HttpResponseMessage(); using (var reader = new StringReader(content)) { string line = reader.ReadLine(); // Extract empty lines. while (string.IsNullOrEmpty(line)) { line = reader.ReadLine(); } // Extract the outer header. while (!string.IsNullOrEmpty(line)) { line = reader.ReadLine(); } // Extract the status code. line = reader.ReadLine(); while (string.IsNullOrEmpty(line)) { line = reader.ReadLine(); } int code = int.Parse(line.Split(' ')[1]); response.StatusCode = (HttpStatusCode)code; // Extract the headers. IDictionary <string, string> headersDic = new Dictionary <string, string>(); while (!string.IsNullOrEmpty((line = reader.ReadLine()))) { var separatorIndex = line.IndexOf(':'); var key = line.Substring(0, separatorIndex).Trim(); var value = line.Substring(separatorIndex + 1).Trim(); // Check if the header already exists, and if so append its value // to the existing value. Fixes issue #548. if (headersDic.ContainsKey(key)) { headersDic[key] = headersDic[key] + ", " + value; } else { headersDic.Add(key, value); } } // Set the content. string mediaType = null; if (headersDic.ContainsKey("Content-Type")) { mediaType = headersDic["Content-Type"].Split(';', ' ')[0]; headersDic.Remove("Content-Type"); } response.Content = new StringContent(reader.ReadToEnd(), Encoding.UTF8, mediaType); // Add the headers to the response. foreach (var keyValue in headersDic) { HttpHeaders headers = response.Headers; // Check if we need to add the current header to the content headers. if (typeof(HttpContentHeaders).GetProperty(keyValue.Key.Replace("-", "")) != null) { headers = response.Content.Headers; } headers.Add(keyValue.Key, keyValue.Value); } // TODO(peleyal): ContentLength header is x while the "real" content that we read from the stream is // Content.ReadStringAsAsync().Length is x+2 } return(response); }
public void HeadForHeaders() { HttpHeaders result = template.HeadForHeaders("head"); Assert.AreEqual("MyValue", result["MyHeader"], "Invalid header"); }
internal static bool TryGetHeader(HttpHeaders headers, HttpContent?content, string name, [NotNullWhen(true)] out IEnumerable <string>?values) { return(headers.TryGetValues(name, out values) || content != null && content.Headers.TryGetValues(name, out values)); }
public static void AddFakeHeaders(this HttpHeaders dict) { dict.Clear(); dict.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); dict.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); }
public static void Replace(this HttpHeaders headers, string header, string value) { //if (headers.Exists(header)) headers.Remove(header); headers.Add(header, value); }
public Dictionary <string, string> CloneHttpHeaders() { return(HttpHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); }
public Result(HttpHeaders headers) { this.Headers = headers.ToDictionary(t => t.Key, t => t.Value.First()); }
public static string GetHttpResponseLog(string statusCode, HttpHeaders headers, string body) { return(GetHttpResponseLog(statusCode, ConvertHttpHeadersToWebHeaderCollection(headers), body)); }
/// <summary> /// Returns a new <see cref="IFullHttpResponse"/> which will be used for as response to the handshake request. /// </summary> /// <param name="req"></param> /// <param name="responseHeaders"></param> /// <returns></returns> protected internal abstract IFullHttpResponse NewHandshakeResponse(IFullHttpRequest req, HttpHeaders responseHeaders);
public Handshaker(WebSocketServerHandshaker serverHandshaker, IChannel channel, HttpHeaders responseHeaders, IPromise completion) { _serverHandshaker = serverHandshaker; _channel = channel; _responseHeaders = responseHeaders; _completion = completion; }
private static bool IsHeaderSet(HttpHeaders headers, string headerName) { IEnumerable <string> dummyOut; return(headers.TryGetValues(headerName, out dummyOut)); }
private void ExpectHasMessageBody(HttpHeaders responseHeaders) { responseHeaders.ContentLength = 1; Expect.Call <HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK).Repeat.Twice(); }
private static ParserState ParseHeaderFields( byte[] buffer, int bytesReady, ref int bytesConsumed, ref HeaderFieldState requestHeaderState, int maximumHeaderLength, ref int totalBytesConsumed, CurrentHeaderFieldStore currentField, HttpHeaders headers) { Contract.Assert((bytesReady - bytesConsumed) >= 0, "ParseHeaderFields()|(inputBufferLength - bytesParsed) < 0"); Contract.Assert(maximumHeaderLength <= 0 || totalBytesConsumed <= maximumHeaderLength, "ParseHeaderFields()|Headers already read exceeds limit."); // Remember where we started. int initialBytesParsed = bytesConsumed; int segmentStart; // Set up parsing status with what will happen if we exceed the buffer. ParserState parseStatus = ParserState.DataTooBig; int effectiveMax = maximumHeaderLength <= 0 ? Int32.MaxValue : maximumHeaderLength - totalBytesConsumed + initialBytesParsed; if (bytesReady < effectiveMax) { parseStatus = ParserState.NeedMoreData; effectiveMax = bytesReady; } Contract.Assert(bytesConsumed < effectiveMax, "We have already consumed more than the max header length."); switch (requestHeaderState) { case HeaderFieldState.Name: segmentStart = bytesConsumed; while (buffer[bytesConsumed] != ':') { if (buffer[bytesConsumed] == '\r') { if (!currentField.IsEmpty()) { parseStatus = ParserState.Invalid; goto quit; } else { // Move past the '\r' requestHeaderState = HeaderFieldState.AfterCarriageReturn; if (++bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.AfterCarriageReturn; } } if (++bytesConsumed == effectiveMax) { string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart); currentField.Name.Append(headerFieldName); goto quit; } } if (bytesConsumed > segmentStart) { string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart); currentField.Name.Append(headerFieldName); } // Move past the ':' requestHeaderState = HeaderFieldState.Value; if (++bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.Value; case HeaderFieldState.Value: segmentStart = bytesConsumed; while (buffer[bytesConsumed] != '\r') { if (++bytesConsumed == effectiveMax) { string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart); currentField.Value.Append(headerFieldValue); goto quit; } } if (bytesConsumed > segmentStart) { string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart); currentField.Value.Append(headerFieldValue); } // Move past the CR requestHeaderState = HeaderFieldState.AfterCarriageReturn; if (++bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.AfterCarriageReturn; case HeaderFieldState.AfterCarriageReturn: if (buffer[bytesConsumed] != '\n') { parseStatus = ParserState.Invalid; goto quit; } if (currentField.IsEmpty()) { parseStatus = ParserState.Done; bytesConsumed++; goto quit; } requestHeaderState = HeaderFieldState.FoldingLine; if (++bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.FoldingLine; case HeaderFieldState.FoldingLine: if (buffer[bytesConsumed] != ' ' && buffer[bytesConsumed] != '\t') { currentField.CopyTo(headers); requestHeaderState = HeaderFieldState.Name; if (bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.Name; } // Unfold line by inserting SP instead currentField.Value.Append(' '); // Continue parsing header field value requestHeaderState = HeaderFieldState.Value; if (++bytesConsumed == effectiveMax) { goto quit; } goto case HeaderFieldState.Value; } quit: totalBytesConsumed += bytesConsumed - initialBytesParsed; return(parseStatus); }
internal HttpHeaderCollection Set(HttpHeaders headers) => headers.Aggregate(this, (h, e) => h.Set(e.Key, e.Value));
internal HandshakeComplete(string requestUri, HttpHeaders requestHeaders, string selectedSubprotocol) { _requestUri = requestUri; _requestHeaders = requestHeaders; _selectedSubprotocol = selectedSubprotocol; }
public ApiRequest() { RawHeaders = new HttpHeaders(); }
public void ServerRequestPushPromise() { this.BootstrapEnv(1, 1, 1); string text = "hello world big time data!"; IByteBuffer content = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text)); string text2 = "hello world smaller data?"; IByteBuffer content2 = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text2)); IFullHttpMessage response = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK, content, true); IFullHttpMessage response2 = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.Created, content2, true); IFullHttpMessage request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, "/push/test", true); try { HttpHeaders httpHeaders = response.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length); httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16); HttpHeaders httpHeaders2 = response2.Headers; httpHeaders2.Set(HttpConversionUtil.ExtensionHeaderNames.Scheme, "https"); httpHeaders2.Set(HttpHeaderNames.Host, "example.org"); httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 5); httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamDependencyId, 3); httpHeaders2.SetInt(HttpHeaderNames.ContentLength, text2.Length); httpHeaders = request.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0); httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16); var http2Headers3 = new DefaultHttp2Headers() { Method = new AsciiString("GET"), Path = new AsciiString("/push/test"), }; Http2TestUtil.RunInChannel(this.clientChannel, () => { this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers3, 0, true, this.NewPromiseClient()); this.clientChannel.Flush(); }); this.AwaitRequests(); var requestCaptor = new ArgumentCaptor <IFullHttpMessage>(); this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => requestCaptor.Capture((IFullHttpMessage)v)))); this.capturedRequests = requestCaptor.GetAllValues(); Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]); IHttp2Headers http2Headers = new DefaultHttp2Headers() { Status = new AsciiString("200") }; // The PUSH_PROMISE frame includes a header block that contains a // complete set of request header fields that the server attributes to // the request. // https://tools.ietf.org/html/rfc7540#section-8.2.1 // Therefore, we should consider the case where there is no Http response status. IHttp2Headers http2Headers2 = new DefaultHttp2Headers() { Scheme = new AsciiString("https"), Authority = new AsciiString("example.org") }; Http2TestUtil.RunInChannel(this.serverConnectedChannel, () => { this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2Headers, 0, false, this.NewPromiseServer()); this.serverHandler.Encoder.WritePushPromiseAsync(this.CtxServer(), 3, 2, http2Headers2, 0, this.NewPromiseServer()); this.serverHandler.Encoder.WriteDataAsync(this.CtxServer(), 3, content.RetainedDuplicate(), 0, true, this.NewPromiseServer()); this.serverHandler.Encoder.WriteDataAsync(this.CtxServer(), 5, content2.RetainedDuplicate(), 0, true, this.NewPromiseServer()); this.serverConnectedChannel.Flush(); }); this.AwaitResponses(); var responseCaptor = new ArgumentCaptor <IFullHttpMessage>(); this.clientListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => responseCaptor.Capture((IFullHttpMessage)v)))); this.capturedResponses = responseCaptor.GetAllValues(); Assert.Equal(response, this.capturedResponses[0]); } finally { request.Release(); response.Release(); response2.Release(); } }
public static string GetHttpRequestLog(string method, string requestUri, HttpHeaders headers, string body) { return(GetHttpRequestLog(method, requestUri, ConvertHttpHeadersToWebHeaderCollection(headers), body)); }
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("uri"); writer.WriteStringValue(Uri); if (HttpHeaders != null && HttpHeaders.Any()) { writer.WritePropertyName("httpHeaders"); writer.WriteStartObject(); foreach (var item in HttpHeaders) { writer.WritePropertyName(item.Key); writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } if (HttpMethod != null) { writer.WritePropertyName("httpMethod"); writer.WriteStringValue(HttpMethod); } if (Timeout != null) { writer.WritePropertyName("timeout"); writer.WriteStringValue(Timeout.Value, "P"); } if (BatchSize != null) { writer.WritePropertyName("batchSize"); writer.WriteNumberValue(BatchSize.Value); } if (DegreeOfParallelism != null) { writer.WritePropertyName("degreeOfParallelism"); writer.WriteNumberValue(DegreeOfParallelism.Value); } writer.WritePropertyName("@odata.type"); writer.WriteStringValue(ODataType); if (Name != null) { writer.WritePropertyName("name"); writer.WriteStringValue(Name); } if (Description != null) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Context != null) { writer.WritePropertyName("context"); writer.WriteStringValue(Context); } if (Inputs != null && Inputs.Any()) { writer.WritePropertyName("inputs"); writer.WriteStartArray(); foreach (var item in Inputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Outputs != null && Outputs.Any()) { writer.WritePropertyName("outputs"); writer.WriteStartArray(); foreach (var item in Outputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); }
/// <summary> /// Handle the web socket handshake for the web socket specification <a href= /// "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and /// 10 share the same wire protocol. /// /// <para> /// Browser request to the server: /// </para> /// /// <![CDATA[ /// GET /chat HTTP/1.1 /// Host: server.example.com /// Upgrade: websocket /// Connection: Upgrade /// Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== /// Sec-WebSocket-Origin: http://example.com /// Sec-WebSocket-Protocol: chat, superchat /// Sec-WebSocket-Version: 8 /// ]]> /// /// <para> /// Server response: /// </para> /// /// <![CDATA[ /// HTTP/1.1 101 Switching Protocols /// Upgrade: websocket /// Connection: Upgrade /// Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= /// Sec-WebSocket-Protocol: chat /// ]]> /// </summary> protected override IFullHttpResponse NewHandshakeResponse(IFullHttpRequest req, HttpHeaders headers) { if (!req.Headers.TryGet(HttpHeaderNames.SecWebsocketKey, out ICharSequence key) || key is null) { ThrowHelper.ThrowWebSocketHandshakeException_MissingKey(); } var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.SwitchingProtocols, req.Content.Allocator.Buffer(0)); if (headers is object) { _ = res.Headers.Add(headers); } string acceptSeed = key + Websocket08AcceptGuid; byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed)); string accept = WebSocketUtil.Base64String(sha1); if (Logger.DebugEnabled) { Logger.WebSocketVersion08ServerHandshakeKey(key, accept); } _ = res.Headers.Add(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket); _ = res.Headers.Add(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade); _ = res.Headers.Add(HttpHeaderNames.SecWebsocketAccept, accept); if (req.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out ICharSequence subprotocols) && subprotocols is object) { string selectedSubprotocol = this.SelectSubprotocol(subprotocols.ToString()); if (selectedSubprotocol is null) { if (Logger.DebugEnabled) { Logger.RequestedSubprotocolNotSupported(subprotocols); } } else { _ = res.Headers.Add(HttpHeaderNames.SecWebsocketProtocol, selectedSubprotocol); } } return(res); }
public void Setup() { headers = new HttpHeadersMock(); }
public Task <T> PutTAsync <T, S>(Uri requestUri, S content, HttpHeaders requestHeaders, CancellationToken cancellationToken) => PutTAsync <T>(requestUri, CreateContent(content, requestHeaders), cancellationToken);
public static ExpandoObject ToExpandoObject(this HttpHeaders headers) { return(headers.ToDictionary(h => h.Key, h => String.Join("; ", h.Value)).ToExpandoObject()); }
public void ServerResponseHeaderInformational() { this.BootstrapEnv(1, 2, 1, 2, 1); IFullHttpMessage request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Put, "/info/test", true); HttpHeaders httpHeaders = request.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.Set(HttpHeaderNames.Expect, HttpHeaderValues.Continue); httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0); httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16); IHttp2Headers http2Headers = new DefaultHttp2Headers() { Method = new AsciiString("PUT"), Path = new AsciiString("/info/test") }; http2Headers.Set(new AsciiString(HttpHeaderNames.Expect.ToString()), new AsciiString(HttpHeaderValues.Continue.ToString())); IFullHttpMessage response = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.Continue); string text = "a big payload"; IByteBuffer payload = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text)); IFullHttpMessage request2 = (IFullHttpMessage)request.Replace(payload); IFullHttpMessage response2 = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK); try { Http2TestUtil.RunInChannel(this.clientChannel, () => { this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers, 0, false, this.NewPromiseClient()); this.clientChannel.Flush(); }); this.AwaitRequests(); httpHeaders = response.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0); IHttp2Headers http2HeadersResponse = new DefaultHttp2Headers() { Status = new AsciiString("100") }; Http2TestUtil.RunInChannel(this.serverConnectedChannel, () => { this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2HeadersResponse, 0, false, this.NewPromiseServer()); this.serverConnectedChannel.Flush(); }); this.AwaitResponses(); httpHeaders = request2.Headers; httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length); httpHeaders.Remove(HttpHeaderNames.Expect); Http2TestUtil.RunInChannel(this.clientChannel, () => { this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 3, payload.RetainedDuplicate(), 0, true, this.NewPromiseClient()); this.clientChannel.Flush(); }); this.AwaitRequests2(); httpHeaders = response2.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0); httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16); IHttp2Headers http2HeadersResponse2 = new DefaultHttp2Headers() { Status = new AsciiString("200") }; Http2TestUtil.RunInChannel(this.serverConnectedChannel, () => { this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2HeadersResponse2, 0, true, this.NewPromiseServer()); this.serverConnectedChannel.Flush(); }); this.AwaitResponses2(); var requestCaptor = new ArgumentCaptor <IFullHttpMessage>(); this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => requestCaptor.Capture((IFullHttpMessage)v))), Times.Exactly(2)); this.capturedRequests = requestCaptor.GetAllValues(); Assert.Equal(2, this.capturedRequests.Count); // We do not expect to have this header in the captured request so remove it now. Assert.NotNull(request.Headers.Remove((AsciiString)"x-http2-stream-weight")); Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]); Assert.Equal(request2, this.capturedRequests[1]); var responseCaptor = new ArgumentCaptor <IFullHttpMessage>(); this.clientListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => responseCaptor.Capture((IFullHttpMessage)v))), Times.Exactly(2)); this.capturedResponses = responseCaptor.GetAllValues(); Assert.Equal(2, this.capturedResponses.Count); Assert.Equal(response, this.capturedResponses[0]); Assert.Equal(response2, this.capturedResponses[1]); } finally { request.Release(); request2.Release(); response.Release(); response2.Release(); } }
public void SetUp() { classUnderTest = new HttpHeaders(); result = classUnderTest.Add(HeaderName, HeaderValue); }
/// <summary> /// Copies current header field to the provided <see cref="HttpHeaders"/> instance. /// </summary> /// <param name="headers">The headers.</param> public void CopyTo(HttpHeaders headers) { headers.Add(_name.ToString(), _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace)); Clear(); }
public void SetUp() { classUnderTest = new HttpHeaders(); }
private AuthenticationHeaderValue CalculateAuthorizationHeaderValue(string httpMethod, string url, HttpHeaders httpHeaders) { var stringToHash = ComputeCanonicalizedHeaders(httpMethod, httpHeaders); stringToHash += ComputeCanonicalizedResource(url); if (stringToHash.EndsWith("\n")) { stringToHash = stringToHash.Substring(0, stringToHash.Length - 1); } using (var hash = new HMACSHA256(accountKey)) { var hashedString = hash.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)); var base64String = Convert.ToBase64String(hashedString); return(new AuthenticationHeaderValue("SharedKey", string.Format("{0}:{1}", accountName, base64String))); } }
public static void PopulateHeaders(this HttpPacket packet, HttpContentHeaders contentHeaders, HttpHeaders generalHeaders) { if (packet == null) throw new ArgumentNullException("packet"); string hdrKey; foreach (var hdr in packet.Headers) { if (hdr.Key == null) continue; hdrKey = hdr.Key.Trim().ToUpperInvariant(); if (hdrKey == "CONTENT-LENGTH") continue; //Content Length is automaitically calculated if (Array.IndexOf<String>(contentOnlyHeaders, hdrKey) >= 0) { //TODO: Confirm if HttpResponseMessage/HttpRequestMessage will break headers into "," commas whereas in actuality header in Packet is an entire header contentHeaders.Add(hdr.Key.Trim(), hdr.Value); } else { generalHeaders.Add(hdr.Key.Trim(), hdr.Value); } //TODO: Check if a string can be parsed properly into the typed header //Test adding multiple headers of the same name will do. // Look up the Add overload that takes an ienumerable<string> to figure out its purpose. } }
private static void AddResponseHeaders(HttpHeaders sourceHeaderCollection, IDictionary<string, string> responseHeaders) { foreach (var header in sourceHeaderCollection) { responseHeaders.Add(header.Key, string.Join(",", header.Value)); } }
public static void TestHeadersInOrder() { string[] c1 = { "E2E4" }; string h_c1 = "Connection: E2E4\r\n"; string[] c2 = { "E7E5" }; string h_c2 = "Connection: E7E5\r\n"; string host = "chez.moi"; string h_host = "Host: " + host + "\r\n"; int ContentLength = 1951; string h_cl = "Content-Length: 1951\r\n"; var hh = new HttpHeaders(); hh.Connection = c1; Assert.AreEqual(h_c1, hh.HeadersInOrder); hh.Host = host; Assert.AreEqual(h_c1 + h_host, hh.HeadersInOrder); hh.Connection = c2; Assert.AreEqual(h_c2 + h_host, hh.HeadersInOrder); hh.Connection = null; Assert.AreEqual(h_host, hh.HeadersInOrder); hh.ContentLength = (uint?) ContentLength; Assert.AreEqual(h_host + h_cl, hh.HeadersInOrder); hh.ContentLength = null; Assert.AreEqual(h_host, hh.HeadersInOrder); hh.Host = null; Assert.IsTrue(String.IsNullOrEmpty(hh.HeadersInOrder)); }
public void Adding_nonstandard_header_name_is_ok() { var headers = new HttpHeaders(); headers.Add("FOOBAR", "123"); headers.GetFirst<string>("FOOBAR").ShouldBe("123"); }
public void HttpHeadersAddTest() { var HttpHeaders = new HttpHeaders(); Assert.AreEqual("[]", HttpHeaders.AsEnumerable<HttpHeader>().ToJsonString()); HttpHeaders.Add("Content-Type", "text/html"); HttpHeaders.Set("Content-Type", "text/plain"); HttpHeaders.Set("cOntEnt-type", "text/plain"); Assert.AreEqual(1, HttpHeaders.Count()); Assert.AreEqual("cOntEnt-type: text/plain", String.Join("|", HttpHeaders.AsEnumerable())); }
public void TestMultipleValueParse() { HttpHeaders headers = new HttpHeaders (); string str = "Key1: Value1\nKey2: Value2\nKey3: Value3"; headers.Parse (new StringReader (str)); Assert.AreEqual ("Value1", headers ["Key1"], "a1"); Assert.AreEqual ("Value2", headers ["Key2"], "a2"); Assert.AreEqual ("Value3", headers ["Key3"], "a3"); Assert.AreEqual (3, headers.Count, "a4"); }