private void ApplyHeaders(HttpHeaders current, IDictionary <string, string> input) { if (input == null) { return; } foreach (var pair in input) { if (pair.Key != null && pair.Value != null) { current.Add(pair.Key, pair.Value); } } }
public void TestParseHeaderValueSafelyOrDefault() { var defaultValue = int.MaxValue; var headersMock = new Mock <HttpHeaders>(); HttpHeaders headers = headersMock.Object; // empty headers test: var result = headers.ParseHeaderValueSafelyOrDefault <int>("DoesNotMatter", int.TryParse, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(defaultValue, result); // valid header test: var headerName = "HeaderName"; var headerValue = 123; headers.Add(headerName, headerValue.ToString()); result = headers.ParseHeaderValueSafelyOrDefault <int>(headerName, int.TryParse, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(headerValue, result); // valid header test: headerName = "MultiValueHeader"; var headerValue1 = 123; var headerValue2 = 321; headers.Add(headerName, new string[] { headerValue1.ToString(), headerValue2.ToString(), }); result = headers.ParseHeaderValueSafelyOrDefault <int>(headerName, int.TryParse, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(headerValue2, result); // invalid header test: result = headers.ParseHeaderValueSafelyOrDefault <int>("WRONG", int.TryParse, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(defaultValue, result); }
public void Exchange() { Uri requestUri = new Uri("http://example.com"); HttpMethod requestMethod = HttpMethod.POST; Expect.Call <bool>(converter.CanRead(typeof(Version), null)).Return(true); MediaType textPlain = new MediaType("text", "plain"); IList <MediaType> mediaTypes = new List <MediaType>(1); mediaTypes.Add(textPlain); Expect.Call <IList <MediaType> >(converter.SupportedMediaTypes).Return(mediaTypes); Expect.Call <IClientHttpRequest>(requestFactory.CreateRequest(requestUri, requestMethod)).Return(request); HttpHeaders requestHeaders = new HttpHeaders(); Expect.Call <HttpHeaders>(request.Headers).Return(requestHeaders).Repeat.Any(); string helloWorld = "Hello World"; Expect.Call <bool>(converter.CanWrite(typeof(string), null)).Return(true); converter.Write(helloWorld, null, request); ExpectGetResponse(); Expect.Call <bool>(errorHandler.HasError(requestUri, requestMethod, response)).Return(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.ContentType = textPlain; Expect.Call <HttpHeaders>(response.Headers).Return(responseHeaders).Repeat.Any(); ExpectHasMessageBody(responseHeaders); Version expected = new Version(1, 0); Expect.Call <bool>(converter.CanRead(typeof(Version), textPlain)).Return(true); Expect.Call <Version>(converter.Read <Version>(response)).Return(expected); Expect.Call <HttpStatusCode>(response.StatusCode).Return(HttpStatusCode.OK); Expect.Call <string>(response.StatusDescription).Return("OK"); mocks.ReplayAll(); HttpHeaders requestMessageHeaders = new HttpHeaders(); requestMessageHeaders.Add("MyHeader", "MyValue"); HttpEntity requestEntity = new HttpEntity(helloWorld, requestMessageHeaders); HttpResponseMessage <Version> result = template.Exchange <Version>("http://example.com", HttpMethod.POST, requestEntity); Assert.AreEqual(expected, result.Body, "Invalid POST result"); Assert.AreEqual(textPlain, result.Headers.ContentType, "Invalid Content-Type"); Assert.AreEqual(textPlain.ToString(), requestHeaders.GetSingleValue("Accept"), "Invalid Accept header"); Assert.AreEqual("MyValue", requestHeaders.Get("MyHeader"), "No custom header set"); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode, "Invalid status code"); Assert.AreEqual("OK", result.StatusDescription, "Invalid status description"); }
/// <summary> /// Copies current header field to the provided <see cref="HttpHeaders"/> instance. /// </summary> /// <param name="headers">The headers.</param> /// <param name="ignoreHeaderValidation">Set to false to validate headers</param> public void CopyTo(HttpHeaders headers, bool ignoreHeaderValidation) { var name = _name.ToString(); var value = _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace); if (ignoreHeaderValidation) { headers.TryAddWithoutValidation(name, value); } else { headers.Add(name, value); } Clear(); }
private static void CreatePlexRequest(HttpHeaders headers, PlexUser user) { headers.Add("X-Plex-Platform", "Windows"); headers.Add("X-Plex-Platform-Version", "NT"); headers.Add("X-Plex-Provides", "player"); headers.Add("X-Plex-Client-Identifier", "Complexion"); headers.Add("X-Plex-Product", "PlexWMC"); headers.Add("X-Plex-Version", "0"); if (user != null) { headers.Add("X-Plex-Token", user.AuthenticationToken); } }
public static bool getUrlOptions(string urlMovie, string keyMovie, ref string buffer, ref string error) { HttpHeaders headers = new HttpHeaders(); headers.Add(new HttpHeader("Referer", urlMovie)); string url = string.Format("https://www.pelispedia.tv/api/iframes.php?id={0}?nocache", keyMovie); HttpManager.requestGet(url, headers, ref buffer, ref error); if (error.Length > 0) { error = "getUrlOptions -> " + error; } return(0 == error.Length); }
private static void AddHeaders(this HttpHeaders headersCollection, Dictionary <string, string> addingHeaders) { if (headersCollection == null || addingHeaders == null) { return; } foreach (var item in addingHeaders) { if (headersCollection.Any(x => string.Equals(x.Key, item.Key, StringComparison.OrdinalIgnoreCase))) { continue; } headersCollection.Add(item.Key, item.Value); } }
public void ClientRequestTrailingHeaders() { this.BootstrapEnv(1, 1, 1); string text = "some data"; IByteBuffer content = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text)); IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, "/some/path/resource2", content, true); try { HttpHeaders httpHeaders = request.Headers; httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3); httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length); httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16); HttpHeaders trailingHeaders = request.TrailingHeaders; trailingHeaders.Set(AsciiString.Of("Foo"), AsciiString.Of("goo")); trailingHeaders.Set(AsciiString.Of("fOo2"), AsciiString.Of("goo2")); trailingHeaders.Add(AsciiString.Of("foO2"), AsciiString.Of("goo3")); var http2Headers = new DefaultHttp2Headers() { Method = new AsciiString("GET"), Path = new AsciiString("/some/path/resource2"), }; IHttp2Headers http2Headers2 = new DefaultHttp2Headers(); http2Headers2.Set(new AsciiString("foo"), new AsciiString("goo")); http2Headers2.Set(new AsciiString("foo2"), new AsciiString("goo2")); http2Headers2.Add(new AsciiString("foo2"), new AsciiString("goo3")); Http2TestUtil.RunInChannel(this.clientChannel, () => { this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers, 0, false, this.NewPromiseClient()); this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 3, content.RetainedDuplicate(), 0, false, this.NewPromiseClient()); this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers2, 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]); } finally { request.Release(); } }
/// <summary> /// Sets the value of an entry in an HttpHeaders collection. If the header does not already exist, it will add /// it. If it does exist, it will overwrite the existing value. /// </summary> /// <param name="headers">The HttpHeaders collection</param> /// <param name="key">The header key to set</param> /// <param name="values">The header values to set</param> private static void Set(this HttpHeaders headers, string key, IEnumerable <string> values) { if (headers == null) { throw new ArgumentNullException("headers"); } if (values == null) { throw new ArgumentNullException("values"); } if (headers.Contains(key)) { headers.Remove(key); } headers.Add(key, values); }
private void ParseTrailers(ReadOnlySpan <byte> span) { // Key-value pairs encoded as a HTTP/1 headers block (without the terminating newline), // per https://tools.ietf.org/html/rfc7230#section-3.2 // // This parsing logic doesn't support line folding. // // JavaScript gRPC-Web trailer parsing logic for comparison: // https://github.com/grpc/grpc-web/blob/55ebde4719c7ad5e58aaa5205cdbd77a76ea9de3/javascript/net/grpc/web/grpcwebclientreadablestream.js#L292-L309 var remainingContent = span; while (remainingContent.Length > 0) { ReadOnlySpan <byte> line; var lineEndIndex = remainingContent.IndexOf(BytesNewLine); if (lineEndIndex == -1) { line = remainingContent; remainingContent = ReadOnlySpan <byte> .Empty; } else { line = remainingContent.Slice(0, lineEndIndex); remainingContent = remainingContent.Slice(lineEndIndex + 2); } if (line.Length > 0) { var headerDelimiterIndex = line.IndexOf((byte)':'); if (headerDelimiterIndex == -1) { throw new InvalidOperationException("Error parsing badly formatted trailing header."); } var name = Encoding.ASCII.GetString(Trim(line.Slice(0, headerDelimiterIndex))); var value = Encoding.ASCII.GetString(Trim(line.Slice(headerDelimiterIndex + 1))); _responseTrailers.Add(name, value); } } }
public static void AddLinkHeader(this HttpHeaders headers, IEnumerable <Link> links) { if (links == null) { throw new ArgumentNullException(nameof(links)); } string headerValue = string.Empty; foreach (var link in links) { headerValue += link.ToLinkHeader(); headerValue += ", "; } headerValue = headerValue.Substring(0, headerValue.Length - 2); headers.Add("Link", headerValue); }
public void Get_Recent_Tags() { var tags = new[] { new Tag() { Id = Guid.NewGuid(), Title = "1", Body = "1", CreateDateUtc = DateTime.UtcNow }, }; // arrange var httpBuilder = new HttpFacadeBuilder(); httpBuilder.WithPostAsync(new HttpResponseMessage(HttpStatusCode.OK)); httpBuilder.WithPostJsonAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(tags))) }); var settings = new Settings { ServerUrl = "https://some.server.net", ProjectName = "testing" }; var serverClient = new ServerClient { HttpFacade = httpBuilder.Build(), Settings = settings }; var headers = new HttpHeaders(); headers.Add("X-Project-Name", "testing"); var response = serverClient.GetRecentTags(10); response.SequenceEqual(tags).Should().BeTrue(); httpBuilder.Mock.Verify( facade => facade.PostJsonAsync(new Uri("https://some.server.net/api/tag"), new RecentTagsRequest(10), headers), Times.Once); }
public void Set(string key, string value) { if (_headers != null) { if (_headers.Contains(key)) { _headers.Remove(key); } _headers.Add(key, value); } if (_headerCollection != null) { if (_headerCollection.AllKeys.Contains(key)) { _headerCollection.Remove(key); } _headerCollection.Add(key, value); } }
/// <summary> /// Extract Tracking Context from http headers, or create a new Tracking Context and /// add it back to the http headers. /// </summary> public static HttpHeaders ProcessHttpHeaders(HttpHeaders headers) { if (headers == null) { return(headers); } // Retrieve the tracking context from the message header, if it exists. if (headers.TryGetValues(TrackingContextKeyName, out IEnumerable <string> values)) { CreateTrackingContextFromHeaderValues(values); } else { // Create a new Tracking Context and copy it to the message header. headers.Add(TrackingContextKeyName, CreateAndSerializeNewTrackingContext()); } return(headers); }
public virtual WebServiceInformation WebServiceEntry(HttpHeaders headers, string name, string url, string method, object data = null) { // Always do initialization even if not logging since the Order is needed var info = ServiceLocator.Get <WebServiceInformation>(Provider); info.Initialize(name, url, method, data); // Set the order in the request headers var httpSettings = ServiceLocator.Get <IHttpClientSettings>(Provider); headers.Add(httpSettings.LogOrderHeader, info.Order); if (!EnabledPreCheck(info)) { return(null); } DoLog(info); return(info); }
/// <summary> add header from current http request </summary> public static void AddFromRequest(this HttpHeaders httpHeaders, string headerName) { IHttpContextAccessor accessor = GeneralContext.GetService <IHttpContextAccessor>(); AppUser appUser = accessor?.HttpContext.Items["loggedUser"] as AppUser; //bool existUserAuthenticated = accessor?.HttpContext?.User?.Identities.Any(x => x.IsAuthenticated) ?? false; if (appUser != null) { //ClaimsPrincipal identityUser = accessor.HttpContext.User; //var claim = accessor.HttpContext.User.Claims.First(c => c.Type == ClaimTypes.UserData.ToString()); //var userJson = Util.DecryptText(claim.Value, authOptions.KEY); //IAppUser loggedUser = JsonConvert.DeserializeObject<AppUser>(userJson); string headerValue = accessor.HttpContext.Request.Headers[headerName]; if (!string.IsNullOrEmpty(headerValue)) { httpHeaders.Add(headerName, headerValue); } } }
public static void OAuthAuthentication(this HttpHeaders headers, IDictionary <string, string> parameters, string signature) { var sb = new StringBuilder(); sb.Append("OAuth "); int i = 0; foreach (var kvp in parameters) { if (i > 0) { sb.Append(","); } sb.Append($"{kvp.Key}=\"{kvp.Value}\""); i++; } sb.Append($",oauth_signature=\"{Uri.EscapeDataString(signature)}\""); headers.Add("Authorization", sb.ToString()); }
public void Search_For_Frames() { var crit = new TerminalSearchCriterionDto(); var frames = new[] { new Frame() { Id = Guid.NewGuid(), }, }; // arrange var httpBuilder = new HttpFacadeBuilder(); httpBuilder.WithPostAsync(new HttpResponseMessage(HttpStatusCode.OK)); httpBuilder.WithPostJsonAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(frames))) }); var settings = new Settings { ServerUrl = "https://some.server.net", ProjectName = "testing" }; var serverClient = new ServerClient { HttpFacade = httpBuilder.Build(), Settings = settings }; var headers = new HttpHeaders(); headers.Add("X-Project-Name", "testing"); var response = serverClient.SearchFrames(crit); response.SequenceEqual(frames).Should().BeTrue(); httpBuilder.Mock.Verify( facade => facade.PostJsonAsync(new Uri("https://some.server.net/api/search/frame"), crit, headers), Times.Once); }
public static void addSucuriHeaders(string jsCrypt, ref HttpHeaders headers) { try { Regex reg = new Regex("S='.+?'", RegexOptions.Singleline); string lin0 = string.Empty; string lin1 = string.Empty; if (reg.IsMatch(jsCrypt)) { string base64 = reg.Match(jsCrypt).Value.Split("'".ToCharArray()[0])[1]; string js = Encoding.UTF8.GetString(Convert.FromBase64String(base64)); string[] lines = getLines(js); string var0 = lines[0].Split('=')[0]; string[] exps0 = lines[0].Substring(lines[0].IndexOf("=") + 1).Split('+'); string[] exps1 = lines[1].Substring(lines[1].IndexOf("=") + 1).Split('+'); foreach (string exp in exps0) { lin0 += evalExp(exp.Trim()); } foreach (string exp in exps1) { lin1 += evalExp(exp.Trim(), var0, lin0); } headers.Add(new HttpHeader("Cookie", lin1)); } } catch (Exception ex) { throw new Exception("HackSucuri.addSucuriHeaders -> " + ex.Message); } }
public void TestParseRateLimitResetHeader() { //X-Rate-Limit-Reset: 1554828920 var defaultValue = DateTimeOffset.MaxValue; var headersMock = new Mock <HttpHeaders>(); HttpHeaders headers = headersMock.Object; // empty headers test: var result = headers.ParseHeaderValueSafelyOrDefault <DateTimeOffset>("DoesNotMatter", DateTimeUtil.TryParseFromUnixTimestampInSecondsString, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(defaultValue, result); // valid header test: var headerName = "X-Rate-Limit-Reset"; var headerValue = "1554828920"; headers.Add(headerName, headerValue.ToString()); result = headers.ParseHeaderValueSafelyOrDefault <DateTimeOffset>(headerName, DateTimeUtil.TryParseFromUnixTimestampInSecondsString, defaultValue); Assert.IsNotNull(result); Assert.AreEqual(DateTimeUtil.ConvertFromUnixTimestampInSeconds(long.Parse(headerValue)), result); }
public static void OAuthAuthentication(this HttpHeaders headers, IToken token) { var sb = new StringBuilder(); sb.Append("OAuth "); int i = 0; foreach (var kvp in token.Parameters) { if (i > 0) { sb.Append(","); } sb.Append($"{kvp.Key}=\"{kvp.Value}\""); i++; } if (string.IsNullOrEmpty(token.Signature)) { token.Sign(); } sb.Append($",oauth_signature=\"{Uri.EscapeDataString(token.Signature)}\""); headers.Add("Authorization", sb.ToString()); }
private void AddCookiesToRequest(HttpHeaders responseHeaders, HttpHeaders requestHeaders) { var cookiehHeaders = responseHeaders.GetValues("Set-Cookie"); foreach (var header in cookiehHeaders) { var cookieParts = header.Split(';'); var cookie = cookieParts[0]; var parts = cookie.Split('='); requestHeaders.Add("Cookie", String.Format("{0}={1}", parts[0], parts[1])); } }
public void AddHeader(string name, string value) { _headers.Add(name, value); }
private void AddAuthCookie(HttpHeaders requestHeaders, string cookieValue) { requestHeaders.Add("Cookie", String.Format("{0}={1}", IdentityCookieName, cookieValue)); }
public void ChunkedRequestWithBodyAndTrailingHeaders() { string text = "foooooo"; string text2 = "goooo"; List <string> receivedBuffers = new List <string>(); this.serverListener .Setup(x => x.OnDataRead( It.IsAny <IChannelHandlerContext>(), It.Is <int>(v => v == 3), It.IsAny <IByteBuffer>(), It.Is <int>(v => v == 0), It.Is <bool>(v => v == false))) .Returns <IChannelHandlerContext, int, IByteBuffer, int, bool>((ctx, id, buf, p, e) => { lock (receivedBuffers) { receivedBuffers.Add(buf.ToString(Encoding.UTF8)); } return(0); }); this.BootstrapEnv(4, 1, 1); IHttpRequest request = new DefaultHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Post, "http://[email protected]:5555/example"); HttpHeaders httpHeaders = request.Headers; httpHeaders.Set(HttpHeaderNames.Host, "www.example.org:5555"); httpHeaders.Add(HttpHeaderNames.TransferEncoding, "chunked"); httpHeaders.Add(AsciiString.Of("foo"), AsciiString.Of("goo")); httpHeaders.Add(AsciiString.Of("foo"), AsciiString.Of("goo2")); httpHeaders.Add(AsciiString.Of("foo2"), AsciiString.Of("goo2")); var http2Headers = new DefaultHttp2Headers() { Method = new AsciiString("POST"), Path = new AsciiString("/example"), Authority = new AsciiString("www.example.org:5555"), Scheme = new AsciiString("http") }; http2Headers.Add(new AsciiString("foo"), new AsciiString("goo")); http2Headers.Add(new AsciiString("foo"), new AsciiString("goo2")); http2Headers.Add(new AsciiString("foo2"), new AsciiString("goo2")); DefaultHttpContent httpContent = new DefaultHttpContent(Unpooled.CopiedBuffer(text, Encoding.UTF8)); ILastHttpContent lastHttpContent = new DefaultLastHttpContent(Unpooled.CopiedBuffer(text2, Encoding.UTF8)); lastHttpContent.TrailingHeaders.Add(AsciiString.Of("trailing"), AsciiString.Of("bar")); IHttp2Headers http2TrailingHeaders = new DefaultHttp2Headers { { new AsciiString("trailing"), new AsciiString("bar") } }; var writePromise = this.NewPromise(); var writeFuture = this.clientChannel.WriteAsync(request, writePromise); var contentPromise = this.NewPromise(); var contentFuture = this.clientChannel.WriteAsync(httpContent, contentPromise); var lastContentPromise = this.NewPromise(); var lastContentFuture = this.clientChannel.WriteAsync(lastHttpContent, lastContentPromise); this.clientChannel.Flush(); Assert.True(writePromise.Task.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(writePromise.IsSuccess); Assert.True(writeFuture.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(writeFuture.IsSuccess()); Assert.True(contentPromise.Task.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(contentPromise.IsSuccess); Assert.True(contentFuture.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(contentFuture.IsSuccess()); Assert.True(lastContentPromise.Task.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(lastContentPromise.IsSuccess); Assert.True(lastContentFuture.Wait(TimeSpan.FromSeconds(WAIT_TIME_SECONDS))); Assert.True(lastContentFuture.IsSuccess()); this.AwaitRequests(); this.serverListener.Verify( x => x.OnHeadersRead( It.IsAny <IChannelHandlerContext>(), It.Is <int>(v => v == 3), It.Is <IHttp2Headers>(v => v.Equals(http2Headers)), It.Is <int>(v => v == 0), It.IsAny <short>(), It.IsAny <bool>(), It.Is <int>(v => v == 0), It.Is <bool>(v => v == false))); this.serverListener.Verify( x => x.OnDataRead( It.IsAny <IChannelHandlerContext>(), It.Is <int>(v => v == 3), It.IsAny <IByteBuffer>(), It.Is <int>(v => v == 0), It.Is <bool>(v => v == false))); this.serverListener.Verify( x => x.OnHeadersRead( It.IsAny <IChannelHandlerContext>(), It.Is <int>(v => v == 3), It.Is <IHttp2Headers>(v => v.Equals(http2TrailingHeaders)), It.Is <int>(v => v == 0), It.IsAny <short>(), It.IsAny <bool>(), It.Is <int>(v => v == 0), It.Is <bool>(v => v == true))); lock (receivedBuffers) { Assert.Single(receivedBuffers); Assert.Equal(text + text2, receivedBuffers[0]); } }
/// <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(); }
private static void AddMessageHeaders(HttpHeaders headers) { headers.Add("N1", new string[] { "V1a", "V1b", "V1c", "V1d", "V1e" }); headers.Add("N2", "V2"); }
/// <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 static void AddLinkHeader(this HttpHeaders headers, ILink link) { var headerValue = link.AsLinkHeader(); headers.Add("Link", headerValue); }
protected override void UpdateHeaders(HttpHeaders headers, DateTime now, Stream stream, string payloadHash = null) { base.UpdateHeaders(headers, now, stream, payloadHash); headers.Add("x-amz-glacier-version", "2012-06-01"); }
/// <summary> /// Adds a key:value pair into the underlying source. If the source already contains the key, the value will be overwritten. /// </summary> /// <param name="key">A string, possibly with constraints dictated by the particular Format this <see cref="T:OpenTracing.Propagation.ITextMap" /> is paired with.</param> /// <param name="value">A String, possibly with constraints dictated by the particular Format this <see cref="T:OpenTracing.Propagation.ITextMap" /> is paired with.</param> public void Set(string key, string value) { // We remove all the existing values for that key before adding the new one to have a "set" behavior _headers.Remove(key); _headers.Add(key, value); }
protected internal override unsafe IFullHttpRequest NewHandshakeRequest() { // Make keys int spaces1 = WebSocketUtil.RandomNumber(1, 12); int spaces2 = WebSocketUtil.RandomNumber(1, 12); int max1 = int.MaxValue / spaces1; int max2 = int.MaxValue / spaces2; int number1 = WebSocketUtil.RandomNumber(0, max1); int number2 = WebSocketUtil.RandomNumber(0, max2); int product1 = number1 * spaces1; int product2 = number2 * spaces2; string key1 = Convert.ToString(product1); string key2 = Convert.ToString(product2); key1 = InsertRandomCharacters(key1); key2 = InsertRandomCharacters(key2); key1 = InsertSpaces(key1, spaces1); key2 = InsertSpaces(key2, spaces2); byte[] key3 = WebSocketUtil.RandomBytes(8); var challenge = new byte[16]; fixed(byte *bytes = challenge) { Unsafe.WriteUnaligned(bytes, number1); Unsafe.WriteUnaligned(bytes + 4, number2); PlatformDependent.CopyMemory(key3, 0, bytes + 8, 8); } this.expectedChallengeResponseBytes = Unpooled.WrappedBuffer(WebSocketUtil.Md5(challenge)); // Get path Uri wsUrl = this.Uri; string path = RawPath(wsUrl); // Format request var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, path); HttpHeaders headers = request.Headers; headers.Add(HttpHeaderNames.Upgrade, Websocket) .Add(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade) .Add(HttpHeaderNames.Host, WebsocketHostValue(wsUrl)) .Add(HttpHeaderNames.Origin, WebsocketOriginValue(wsUrl)) .Add(HttpHeaderNames.SecWebsocketKey1, key1) .Add(HttpHeaderNames.SecWebsocketKey2, key2); string expectedSubprotocol = this.ExpectedSubprotocol; if (!string.IsNullOrEmpty(expectedSubprotocol)) { headers.Add(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol); } if (this.CustomHeaders != null) { headers.Add(this.CustomHeaders); } // Set Content-Length to workaround some known defect. // See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html headers.Set(HttpHeaderNames.ContentLength, key3.Length); request.Content.WriteBytes(key3); return(request); }
public IHttpAction Handle(Request request) { if (request.Object.Method == "GET" || request.Object.Method == "HEAD") { var includeBody = request.Object.Method != "HEAD"; var httpHeaders = new HttpHeaders(); var fileSystem = new FileSystem(Path.Combine(DirectoryRoot, "www", request.VirtualHost.Directory, request.Object.Uri.Url), request.VirtualHost.DefaultIndex); var fileDescription = fileSystem.GetFile(); if (fileDescription == null) { return(new NotFound(includeBody)); } var dateChange = new HttpDate(fileDescription.GetLastModified()); httpHeaders.Add("Content-Type", HttpMimeType.GetByExtension(fileDescription.GetExtension()) + "; charset=" + fileDescription.GetEncoding()); httpHeaders.Add("Last-Modified", dateChange.ToString()); if (request.Object.HttpRange != null) { try { request.Object.HttpRange.Normalize(fileDescription.GetFileSize() - 1); var bytesArray = fileDescription.GetRangeBytes(request.Object.HttpRange); if (bytesArray.Length > 0) { httpHeaders.Add("Content-Range", request.Object.HttpRange.ToString()); return(new PartialContent(httpHeaders, bytesArray, includeBody)); } else { return(new NotSatisfiable(includeBody)); } } catch (Exception) { request.Object.HttpRange = null; } } if (request.Object["If-Modified-Since"] != null) { try { var requestDate = DateTime.Parse(request.Object["If-Modified-Since"].Trim()); if (requestDate >= dateChange.DateTime) { return(new NotModified(httpHeaders, includeBody)); } } catch { // ignored } } return(new Ok(httpHeaders, fileDescription.GetAllBytes(), includeBody)); } return(NextHandler != null?NextHandler.Handle(request) : new NotImplemented()); }
/// <summary> /// Copies current header field to the provided <see cref="HttpHeaders"/> instance. /// </summary> /// <param name="headers">The headers.</param> /// <param name="ignoreHeaderValidation">Set to false to validate headers</param> public void CopyTo(HttpHeaders headers, bool ignoreHeaderValidation) { var name = _name.ToString(); var value = _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace); if (ignoreHeaderValidation) { headers.TryAddWithoutValidation(name, value); } else { headers.Add(name, value); } Clear(); }
private static void AddMessageHeaders(HttpHeaders headers) { headers.Add("N1", new string[] { "V1a", "V1b", "V1c", "V1d", "V1e" }); headers.Add("N2", "V2"); }
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. } }
public void Adding_nonstandard_header_name_is_ok() { var headers = new HttpHeaders(); headers.Add("FOOBAR", "123"); headers.GetFirst<string>("FOOBAR").ShouldBe("123"); }
/// <summary> /// Populates contentheaders and generalheaders with headers from the <see cref="HttpPacket"/>> /// </summary> /// <param name="packet"></param> /// <param name="contentHeaders"></param> /// <param name="generalHeaders"></param> public static void PopulateHeaders(this HttpPacket packet, HttpContentHeaders contentHeaders, HttpHeaders generalHeaders) { if (packet == null) throw new ArgumentNullException("packet"); bool dateHeaderProcessed = false; 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 automatically calculated by System.Net.Http.ByteArrayContent } else if (hdrKey == "DATE") { if (dateHeaderProcessed) continue; //Already Processed dateHeaderProcessed = true; //Date Header in wrong format causes exception in System.Net.Http.HttpResponseMessage/HttpRequestMessage //TODO: Confirm that this exception still occurs in the newer Nuget version of System.Net.Http //Check if the date string is in RFC 1123 format var val = (hdr.Value == null || !hdr.Value.Any()) ? null : hdr.Value.First().Trim(); if(val != null && Common.Shared.IsValidHttpDate(val)) { generalHeaders.Add("Date", val); } continue; } if (Array.IndexOf<String>(contentOnlyHeaders, hdrKey) >= 0) { contentHeaders.Add(hdr.Key.Trim(), hdr.Value); } else { generalHeaders.Add(hdr.Key.Trim(), hdr.Value); } } }
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())); }