private ControlResponse ProcessControlRequestInternal(ControlRequest request) { var soap = new XmlDocument(); soap.LoadXml(request.InputXml); var sparams = new Headers(); var body = soap.GetElementsByTagName("Body", NS_SOAPENV).Item(0); var method = body.FirstChild; foreach (var p in method.ChildNodes) { var e = p as XmlElement; if (e == null) { continue; } sparams.Add(e.LocalName, e.InnerText.Trim()); } Logger.Debug("Received control request {0}", method.LocalName); var result = GetResult(method.LocalName, sparams); var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", string.Empty)); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI); rbody.AppendChild(response); foreach (var i in result) { var ri = env.CreateElement(i.Key); ri.InnerText = i.Value; response.AppendChild(ri); } var xml = env.OuterXml.Replace("xmlns:m=", "xmlns:u="); var controlResponse = new ControlResponse { Xml = xml, IsSuccessful = true }; //Logger.Debug(xml); controlResponse.Headers.Add("EXT", string.Empty); return controlResponse; }
public static void CollectHeaders(Stream inputStream, Headers headers) { while (true) { // Collect Headers string[] parts = ReadKeyValue (inputStream); if (parts == null) { break; } headers.Add (parts [0], parts [1]); } }
public static Headers ReadHeaders(Stream stream) { HeaderFields field; var fields = new Headers(); var reader = new BinaryReader(stream); do { field = (HeaderFields)reader.ReadByte(); var size = reader.ReadInt16(); fields.Add(field, reader.ReadBytes(size)); } while (field != HeaderFields.EndOfHeader); return fields; }
//Обобщенный метод GET/POST запроса string Request(string address, string Method, string body = "") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); request.Method = Method; SetProxy(ref request); SetAllowAutoRedirect(ref request); AddHeaders(request, Headers); AddCookies(request); switch (Method) { case "GET": break; case "POST": //Формирование тела POST запроса UTF8Encoding encoding = new UTF8Encoding();///// byte[] bytePostData = encoding.GetBytes(body); request.ContentLength = bytePostData.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(bytePostData, 0, bytePostData.Length); } break; } HttpWebResponse responce = (HttpWebResponse)request.GetResponse(); Stream dataStream = responce.GetResponseStream(); string HtmlResponse; using (StreamReader reader = new StreamReader(dataStream)) { HtmlResponse = reader.ReadToEnd(); } _responceUri = responce.ResponseUri; _responceStatus = (int)responce.StatusCode; //Обновление куки CookieCollection bufCookies = new CookieCollection(); if (responce.Cookies.Count != 0) { foreach (Cookie cookieResponce in responce.Cookies) { bool isNewCookie = true; foreach (Cookie cookieRequest in _cookie) { if (cookieRequest.Name == cookieResponce.Name) { isNewCookie = false; bufCookies.Add(cookieResponce); break; } } if (isNewCookie) { bufCookies.Add(cookieResponce); } } _cookie = bufCookies; } //Установка заголовка Cookie if (responce.Headers.Get("Set-Cookie") != null) { if (Headers.Get("Cookie") != null) { Headers.Set(HttpRequestHeader.Cookie, responce.Headers.Get("Set-Cookie")); } else { Headers.Add(HttpRequestHeader.Cookie, responce.Headers.Get("Set-Cookie")); } } ResponceHeaders = responce.Headers; responce.Close(); return(HtmlResponse); }
public HttpResponse WithHeader(string name, params string[] value) { Headers.Add(new Header(name, value)); return(this); }
private RequestData( HttpMethod method, PostData data, IConnectionConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory ) { ConnectionSettings = global; MemoryStreamFactory = memoryStreamFactory; Method = method; PostData = data; if (data != null) { data.DisableDirectStreaming = local?.DisableDirectStreaming ?? global.DisableDirectStreaming; } Pipelined = local?.EnableHttpPipelining ?? global.HttpPipeliningEnabled; HttpCompression = global.EnableHttpCompression; RequestMimeType = local?.ContentType ?? MimeType; Accept = local?.Accept ?? MimeType; if (global.Headers != null) { Headers = new NameValueCollection(global.Headers); } if (local?.Headers != null) { Headers ??= new NameValueCollection(); foreach (var key in local.Headers.AllKeys) { Headers[key] = local.Headers[key]; } } if (!string.IsNullOrEmpty(local?.OpaqueId)) { Headers ??= new NameValueCollection(); Headers.Add(OpaqueIdHeader, local.OpaqueId); } RunAs = local?.RunAs; SkipDeserializationForStatusCodes = global?.SkipDeserializationForStatusCodes; ThrowExceptions = local?.ThrowExceptions ?? global.ThrowExceptions; RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout; PingTimeout = local?.PingTimeout ?? global.PingTimeout ?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout); KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000); KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000); DnsRefreshTimeout = global.DnsRefreshTimeout; ProxyAddress = global.ProxyAddress; ProxyUsername = global.ProxyUsername; ProxyPassword = global.ProxyPassword; DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection; BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials; ApiKeyAuthenticationCredentials = local?.ApiKeyAuthenticationCredentials ?? global.ApiKeyAuthenticationCredentials; AllowedStatusCodes = local?.AllowedStatusCodes ?? EmptyReadOnly <int> .Collection; ClientCertificates = local?.ClientCertificates ?? global.ClientCertificates; UserAgent = global.UserAgent; TransferEncodingChunked = local?.TransferEncodingChunked ?? global.TransferEncodingChunked; TcpStats = local?.EnableTcpStats ?? global.EnableTcpStats; ThreadPoolStats = local?.EnableThreadPoolStats ?? global.EnableThreadPoolStats; }
/// <summary> /// 有关额外的请求Header /// </summary> public void GenshinExtraHeader() { Headers.Add("x-rpc-client_type", Config.ClientType); Headers.Add("x-rpc-app_version", Config.AppVersion); Headers.Add("DS", Config.GetDs()); }
/// <summary> /// Adds the header. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> public void AddHeader(string name, string value) { Headers.Add(name, new WireMockList <string>(value)); }
public void CopyFrom(IBasicProperties basicProperties) { Preconditions.CheckNotNull(basicProperties, "basicProperties"); if (basicProperties.IsContentTypePresent()) { ContentType = basicProperties.ContentType; } if (basicProperties.IsContentEncodingPresent()) { ContentEncoding = basicProperties.ContentEncoding; } if (basicProperties.IsDeliveryModePresent()) { DeliveryMode = basicProperties.DeliveryMode; } if (basicProperties.IsPriorityPresent()) { Priority = basicProperties.Priority; } if (basicProperties.IsCorrelationIdPresent()) { CorrelationId = basicProperties.CorrelationId; } if (basicProperties.IsReplyToPresent()) { ReplyTo = basicProperties.ReplyTo; } if (basicProperties.IsExpirationPresent()) { Expiration = basicProperties.Expiration; } if (basicProperties.IsMessageIdPresent()) { MessageId = basicProperties.MessageId; } if (basicProperties.IsTimestampPresent()) { Timestamp = basicProperties.Timestamp.UnixTime; } if (basicProperties.IsTypePresent()) { Type = basicProperties.Type; } if (basicProperties.IsUserIdPresent()) { UserId = basicProperties.UserId; } if (basicProperties.IsAppIdPresent()) { AppId = basicProperties.AppId; } if (basicProperties.IsClusterIdPresent()) { ClusterId = basicProperties.ClusterId; } if (basicProperties.IsHeadersPresent()) { foreach (var header in basicProperties.Headers) { Headers.Add(header.Key, header.Value); } } }
public RedirectResult(string location) : base(HttpResponseStatusCode.SeeOther) { Headers.Add(new HttpHeader(GlobalConstants.LocationHeaderKey, location)); }
public void SetContent(object content, string contentType) { Headers.Add("Content-Type", contentType); Content = (HttpContent)content; }
public WhatsOnChain(NetworkType networkType = NetworkType.Main) { Network = networkType.GetDescriptor(); Headers.Add("Content-Type", WebContentType.Json); Headers.Add("User-Agent", "KzApiWhatsOnChain"); }
public HttpRequest header(string name, string value) { Headers.Add(name, value); return(this); }
public TextFileResponse(string fileName) : base(StatusCode.OK) { FileName = fileName; Headers.Add(Header.ContentType, ContentType.PlainText); }
/// <summary> /// Appends a <paramref name="value"/> to the specified HTTP header sent with the response. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to append /// <paramref name="value"/> to. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value to append to the header. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> or <paramref name="value"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current headers cannot allow the header to append a value. /// </exception> public void AppendHeader(string name, string value) { Headers.Add(name, value); }
private ControlResponse ProcessControlRequestInternal(ControlRequest request) { var soap = new XmlDocument(); soap.LoadXml(request.InputXml); var sparams = new Headers(); var body = soap.GetElementsByTagName("Body", NS_SOAPENV).Item(0); var method = body.FirstChild; foreach (var p in method.ChildNodes) { var e = p as XmlElement; if (e == null) { continue; } sparams.Add(e.LocalName, e.InnerText.Trim()); } var deviceId = "fgd"; var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", "yes")); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); IEnumerable<KeyValuePair<string, string>> result; _logger.Debug("Received control request {0}", method.Name); var user = _user; if (string.Equals(method.LocalName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase)) result = HandleGetSearchCapabilities(); else if (string.Equals(method.LocalName, "GetSortCapabilities", StringComparison.OrdinalIgnoreCase)) result = HandleGetSortCapabilities(); else if (string.Equals(method.LocalName, "GetSystemUpdateID", StringComparison.OrdinalIgnoreCase)) result = HandleGetSystemUpdateID(); else if (string.Equals(method.LocalName, "Browse", StringComparison.OrdinalIgnoreCase)) result = HandleBrowse(sparams, user, deviceId); else if (string.Equals(method.LocalName, "X_GetFeatureList", StringComparison.OrdinalIgnoreCase)) result = HandleXGetFeatureList(); else if (string.Equals(method.LocalName, "X_SetBookmark", StringComparison.OrdinalIgnoreCase)) result = HandleXSetBookmark(sparams, user); else if (string.Equals(method.LocalName, "Search", StringComparison.OrdinalIgnoreCase)) result = HandleSearch(sparams, user, deviceId); else throw new ResourceNotFoundException("Unexpected control request name: " + method.LocalName); var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI); rbody.AppendChild(response); foreach (var i in result) { var ri = env.CreateElement(i.Key); ri.InnerText = i.Value; response.AppendChild(ri); } var controlResponse = new ControlResponse { Xml = env.OuterXml, IsSuccessful = true }; controlResponse.Headers.Add("EXT", string.Empty); return controlResponse; }
/// <summary> /// Initializes a new instance of the <see cref="DeflateResponse" /> class. /// </summary> /// <param name="res">The res.</param> public DeflateResponse(IServerResponse res) : base(res) { Headers.Add("Content-Encoding", "deflate"); deflateStream = new DeflateStream(base.OutputStream, CompressionMode.Compress, true); }
private void NotifyDevice(UpnpDevice dev, string type, bool sticky) { _logger.Debug("NotifyDevice"); var headers = new Headers(true); headers.Add("HOST", "239.255.255.250:1900"); headers.Add("CACHE-CONTROL", "max-age = 600"); headers.Add("LOCATION", dev.Descriptor.ToString()); headers.Add("SERVER", _serverSignature); headers.Add("NTS", "ssdp:" + type); headers.Add("NT", dev.Type); headers.Add("USN", dev.USN); SendDatagram(_ssdpEndp, String.Format("NOTIFY * HTTP/1.1\r\n{0}\r\n", headers.HeaderBlock), sticky); _logger.Debug("{0} said {1}", dev.USN, type); }
public void AddNewHeader() { Headers.Add(new KeyVal("Header-Key", "Header-Value")); RaisePropertyChanged("Headers"); }
protected virtual void Append(string key, string value) { Headers.Add(key, value); }
public void AddHeader(string key, string value) { Headers.Add(key, value); }
internal OutboundMessageContent(IMessage message) : base(message) { Headers.ContentType = MediaTypeHeaderValue.Parse(message.Type.ToString()); Headers.Add(MessageNameHeader, message.Name); }
public void AddHeader(string header, string value) { Headers.Add(h => h.Add(header, value)); }
private void InitilizeHeaders() { if (AutoGenerateColumns && !headerInitilized) { headerInitilized = true; DataType.GetProperties().Where(p => !IgnoreProperties.Contains(p.Name)).Reverse().ToList().ForEach(property => { if (Headers.Any(x => x.Property?.Name == property.Name)) { return; } var attrs = property.GetCustomAttributes(true); if (attrs.OfType <TableIgnoreAttribute>().Any()) { Headers.Add(new TableHeader() { Ignore = true, Property = property }); return; } var columnConfig = attrs.OfType <TableColumnAttribute>().FirstOrDefault() ?? new TableColumnAttribute() { Text = property.Name }; if (columnConfig.Ignore) { Headers.Add(new TableHeader() { Ignore = true, Property = property }); return; } var editorConfig = attrs.OfType <EditorGeneratorAttribute>().FirstOrDefault() ?? new EditorGeneratorAttribute() { Control = typeof(BInput <string>) }; var formConfig = attrs.OfType <FormControlAttribute>().FirstOrDefault(); var propertyConfig = attrs.OfType <PropertyAttribute>().FirstOrDefault(); var tableHeader = new TableHeader() { EvalRaw = row => { object value = property.GetValue(row); return(value); }, SortNo = columnConfig.SortNo, IsCheckBox = property.PropertyType == typeof(bool) || Nullable.GetUnderlyingType(property.PropertyType) == typeof(bool), Property = property, Text = columnConfig.Text, Width = columnConfig.Width, IsEditable = columnConfig.IsEditable }; tableHeader.Eval = displayRender.CreateRenderFactory(tableHeader).CreateRender(tableHeader); if (IsEditable && columnConfig.IsEditable) { InitilizeHeaderEditor(property, editorConfig, tableHeader); } Headers.Insert(0, tableHeader); } ); if (IsEditable) { CreateOperationColumn(); } chkAll?.MarkAsRequireRender(); ResetSelectAllStatus(); } else if (!AutoGenerateColumns && !headerInitilized && Headers.Any()) { headerInitilized = true; foreach (var header in Headers) { if (!CanEdit(header)) { continue; } InitilizeHeaderEditor(header.Property, header.Property.GetCustomAttribute <EditorGeneratorAttribute>() ?? new EditorGeneratorAttribute(), header); } CreateOperationColumn(); Refresh(); } }
public void AddHeader(Action <HttpRequestHeaders> headers) { Headers.Add(headers); }
public HtmlResult(string content, HttpResponseStatusCode responseStatusCode) : base(responseStatusCode) { Headers.Add(new HttpHeader(GlobalConstants.ContentType, "text/html")); Content = Encoding.UTF8.GetBytes(content); }
public HtmlResult(string content, HttpResponseStatusCode responseStatusCode) : base(responseStatusCode) { Headers.Add(new HttpHeader("Content-Type", "text/html")); Headers.Add(new HttpHeader("X-Frame-Options", "allow-from https://youtube.com/")); Content = Encoding.UTF8.GetBytes(content); }
public void AddHeader(HttpHeader header) { Validator.ThrowIfNull(header, nameof(header)); Headers.Add(header); }
public RedirectResult(string location) : base(HttpResponseStatusCode.Redirect) { Headers.Add(new HttpHeader(HttpHeader.Location, location)); }
private ControlResponse ProcessControlRequestInternal(ControlRequest request) { var soap = new XmlDocument(); soap.LoadXml(request.InputXml); var sparams = new Headers(); var body = soap.GetElementsByTagName("Body", NS_SOAPENV).Item(0); var method = body.FirstChild; foreach (var p in method.ChildNodes) { var e = p as XmlElement; if (e == null) { continue; } sparams.Add(e.LocalName, e.InnerText.Trim()); } Logger.Debug("Received control request {0}", method.LocalName); var result = GetResult(method.LocalName, sparams); var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", string.Empty)); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI); rbody.AppendChild(response); foreach (var i in result) { var ri = env.CreateElement(i.Key); ri.InnerText = i.Value; response.AppendChild(ri); } var xml = env.OuterXml.Replace("xmlns:m=", "xmlns:u="); var controlResponse = new ControlResponse { Xml = xml, IsSuccessful = true }; //Logger.Debug(xml); controlResponse.Headers.Add("EXT", string.Empty); return(controlResponse); }
/// <summary> /// Initializes a new instance of the <see cref="PostDataRequest"/> class. /// </summary> /// <param name="data">The data.</param> public PostDataRequest(string data) { DataString = data; RequestBody = new StringContent(data); Headers.Add("Content-type", "text/xml"); }
private void readData(string key, string value) { try { switch (key) { case SourceKey: Source = value; break; case MessageTypeKey: MessageType = value; break; case ReplyUriKey: ReplyUri = new Uri(value); break; case ContentTypeKey: ContentType = value; break; case CorrelationIdKey: if (Guid.TryParse(value, out var originalId)) { CorrelationId = originalId; } break; case SagaIdKey: SagaId = value; break; case ParentIdKey: if (Guid.TryParse(value, out var parentId)) { CausationId = parentId; } break; case DestinationKey: Destination = new Uri(value); break; case AcceptedContentTypesKey: AcceptedContentTypes = value.Split(','); break; case IdKey: if (Guid.TryParse(value, out var id)) { Id = id; } break; case ReplyRequestedKey: ReplyRequested = value; break; case AckRequestedKey: AckRequested = value.Equals("true", StringComparison.OrdinalIgnoreCase); break; case ExecutionTimeKey: ExecutionTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Utc); break; case AttemptsKey: Attempts = Int32.Parse(value); break; case DeliverByHeader: DeliverBy = DateTime.Parse(value); break; case SentAttemptsHeaderKey: SentAttempts = Int32.Parse(value); break; case ReceivedAtKey: ReceivedAt = new Uri(value); break; default: Headers.Add(key, value); break; } } catch (Exception e) { throw new InvalidOperationException($"Error trying to read data for {key} = '{value}'", e); } }
/// <summary> /// Parses Request Http Headers from an array of strings /// into the Headers property of this class. /// </summary> /// <param name="lines">Array of Http Headers to parse in header: value format</param> public void ParseHttpHeaders(string[] lines) { Headers.Clear(); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; if (string.IsNullOrEmpty(line)) { continue; } int idx = line.IndexOf(':'); if (idx < 0 || line.Length < idx + 2) { continue; } string header = line.Substring(0, idx); string value = line.Substring(idx + 1).Trim(); var hd = new HttpRequestHeader { Name = header, Value = value }; var name = hd.Name.ToLower(); // ignore host header - host is part of url if (name == "host") { Host = hd.Value; continue; } if (name == "content-type") { ContentType = hd.Value; if (!string.IsNullOrEmpty(hd.Value)) { TextEncoding = StringUtils.ExtractString(hd.Value, "charset=", ";", false, true); // Web Content defaults to UTF-8 if (string.IsNullOrEmpty(TextEncoding)) { TextEncoding = "UTF-8"; } } } if (name == "content-length") { continue; // HTTP client adds this automatically } if (name == "websurge-request-inactive") { IsActive = false; continue; // don't add header } if (name == "websurge-request-name") { Name = hd.Value; continue; } if (name == "websurge-request-sortnorandomize") { SortNoRandmomize = true; continue; } Headers.Add(hd); } }
public TextResult(string content, HttpResponseStatusCode responseStatusCode) : base(responseStatusCode) { Headers.Add(new HttpHeader("Content-Type", "text/plain")); Content = Encoding.UTF8.GetBytes(content); }
public RedirectResult(string location, string content) : base(content, HttpResponseStatusCode.SeeOther) { Headers.Add(new HttpHeader(Constants.LocationHeaderKey, location)); }
private IEnumerable<KeyValuePair<string, string>> HandleGetSystemUpdateID() { var headers = new Headers(true); headers.Add("Id", _systemUpdateId.ToString(_usCulture)); return headers; }
private void SendSearchResponse(IPEndPoint endpoint, UpnpDevice dev) { var headers = new Headers(true); headers.Add("CACHE-CONTROL", "max-age = 600"); headers.Add("DATE", DateTime.Now.ToString("R")); headers.Add("EXT", ""); headers.Add("LOCATION", dev.Descriptor.ToString()); headers.Add("SERVER", _serverSignature); headers.Add("ST", dev.Type); headers.Add("USN", dev.USN); SendDatagram(endpoint, String.Format("HTTP/1.1 200 OK\r\n{0}\r\n", headers.HeaderBlock), false); _logger.Info("{1} - Responded to a {0} request", dev.Type, endpoint); }