private static void SetContentType(HttpWebRequest request, RequestContentType contentType, string boundary = null) { switch (contentType) { case RequestContentType.UrlEncoded: request.ContentType = "application/x-www-form-urlencoded"; break; case RequestContentType.Multipart: if (string.IsNullOrWhiteSpace(boundary)) { throw new ArgumentNullException(nameof(boundary), $"Argument '{nameof(boundary)}' cannot be null or empty while argument '{nameof(contentType)}' value is '{RequestContentType.Multipart}'."); } request.ContentType = $"multipart/form-data; boundary={boundary}"; break; case RequestContentType.Json: request.ContentType = "application/json"; break; case RequestContentType.Xml: request.ContentType = "application/xml"; break; } }
public ChannelRequest(RequestContentType contentType) { if (Parameters == null) { Parameters = new ChannelMethodParameters(contentType); } }
/// <summary> /// 从请求流中反序列化构造参数值 /// </summary> /// <param name="p"></param> /// <param name="requst"></param> /// <returns></returns> public virtual object FromBodyDeserializeObject(ParameterInfo p, HttpRequest requst) { // 从请求流中反序列化对象中,要注意三点: // 1、忽略参数的名称 // 2、直接使用参数类型,不做可空类型处理 // 3、仅支持 JSON, XML 的数据格式 SerializeFormat format = RequestContentType.GetFormat(requst.ContentType); if (format == SerializeFormat.Json) { string text = requst.GetPostText(); return(JsonExtensions.FromJson(text, p.ParameterType)); } if (format == SerializeFormat.Xml) { string text = requst.GetPostText(); return(XmlExtensions.FromXml(text, p.ParameterType)); } // 仅仅是需要读取整个请求流字符串, // 而且目标类型已经是字符串,就没有必要反序列化了,所以就直接以字符串返回 if (p.ParameterType == typeof(string)) { return(requst.GetPostText()); } throw new NotSupportedException("[FromBody]标记只能配合 JSON/XML 数据格式来使用。"); }
public ChannelMethodParameters(RequestContentType contentType) { if (_parameters == null) { _parameters = new List <ChannelMethodParameter>(); } ContentType = contentType; }
public static string AsContentTypeString(this RequestContentType requestContentType) { var contentType = "application/json"; if (requestContentType == RequestContentType.ApplicationXml) { contentType = "application/xml"; } return(contentType); }
public static HttpResponse Put(string url, Stream content = null, RequestContentType contentType = RequestContentType.NotSpecified, string boundary = null, WebHeaderCollection headers = null, CookieCollection cookies = null, int?timeout = null, ICredentials credentials = null, RequestCachePolicy cachePolicy = null, X509Certificate2 clientCert = null, RemoteCertificateValidationCallback validateCallback = null) { try { var request = CreateRequest(url, HttpMethod.Put, headers, cookies, timeout, credentials, cachePolicy, clientCert, validateCallback); SetContentType(request, contentType, boundary); if (content == null) { request.ContentLength = 0; } else { request.ContentLength = content.Length; if (content.CanSeek) { request.ContentLength = content.Length - content.Position; } StreamUtil.StreamCopy(content, request.GetRequestStream()); } return(CreateResponse(GetResponse(request))); } catch (ThreadAbortException) { throw; } catch (StackOverflowException) { throw; } catch (OutOfMemoryException) { throw; } catch (WebException ex) { if (ex.Response != null) { return(CreateResponse((HttpWebResponse)ex.Response)); } switch (ex.Status) { case WebExceptionStatus.NameResolutionFailure: // DNS resolve error. break; } throw ex; } catch (Exception) { throw; } }
/// <summary> /// Builds a memory stream for failure responses. /// </summary> /// <param name="errorMessage">Error message</param> /// <param name="acceptContentType">Type of serialization</param> /// <param name="acceptEncoding">Response encoding</param> /// <returns></returns> private static MemoryStream BuildFailureResponse(string errorMessage, RequestContentType acceptContentType, Encoding acceptEncoding) { MemoryStream responseStream; var httpError = new HttpError(errorMessage); var serializer = new XmlSerializer(typeof(HttpError)); switch (acceptContentType) { case RequestContentType.Json: using (var stream = new MemoryStream()) { // Serialize the object to Xml: serializer.Serialize(stream, httpError); stream.Position = 0; // Load the xml stream to a XmlDocument: var xmlDoc = new XmlDocument(); xmlDoc.Load(stream); // Remove the namespace attributes: if (xmlDoc.DocumentElement?.Attributes != null) { xmlDoc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); xmlDoc.DocumentElement.Attributes.RemoveNamedItem("xmlns:xsd"); xmlDoc.DocumentElement.Attributes.RemoveNamedItem("xmlns:xsi"); } // Serialize the XmlElement to JSON: var serialized = Json.JsonConverter.ConvertFromXml(xmlDoc.DocumentElement); responseStream = new MemoryStream(acceptEncoding.GetBytes(serialized)); } break; case RequestContentType.Xml: case RequestContentType.Unknown: default: responseStream = new MemoryStream(); serializer.Serialize(responseStream, httpError); break; } responseStream.Position = 0; return(responseStream); }
public static HttpClient SetContentType(this HttpClient self, RequestContentType type) { switch (type) { case RequestContentType.Json: self.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); break; case RequestContentType.Text: self.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("text/html")); break; default: throw new ArgumentOutOfRangeException(); } return(self); }
/// <summary> /// Builds a memory stream from the response body. /// </summary> /// <param name="response">Response message</param> /// <param name="acceptContentType">Content type to use for serialization</param> /// <param name="acceptEncoding">Response encoding</param> /// <returns>Memory stream from data serialized by content type</returns> private static MemoryStream BuildSuccessResponse(Response response, RequestContentType acceptContentType, Encoding acceptEncoding) { var bodyString = string.Empty; // If Body is null, just return empty response if (response?.Body == null) { return new MemoryStream(acceptEncoding.GetBytes(bodyString)) { Position = 0 } } ; if (response.Body.Payload.XmlData != null) { switch (acceptContentType) { case RequestContentType.Json: // Remove the namespace attributes: response.Body.Payload.XmlData.Attributes.RemoveNamedItem("xmlns"); response.Body.Payload.XmlData.Attributes.RemoveNamedItem("xmlns:xsd"); response.Body.Payload.XmlData.Attributes.RemoveNamedItem("xmlns:xsi"); bodyString = Json.JsonConverter.ConvertFromXml(response.Body.Payload.XmlData); break; case RequestContentType.Xml: bodyString = response.Body.Payload.XmlData.OuterXml; break; } } else if (!string.IsNullOrEmpty(response.Body.Payload.Data)) { bodyString = XmlString.Decode(response.Body.Payload.Data); } return(new MemoryStream(acceptEncoding.GetBytes(bodyString)) { Position = 0 }); }
static string requestTypeString(RequestContentType type) { string ret = ""; switch (type) { case RequestContentType.Json: { ret = "application/json"; break; } case RequestContentType.Xml: { ret = "application/xml"; break; } case RequestContentType.Html: { ret = "text/html"; break; } case RequestContentType.Text: { ret = "text/plain"; break; } case RequestContentType.Gif: case RequestContentType.Img: case RequestContentType.Png: default: { ret = "application/octet-stream"; break; } } return(ret); }
public static string PostData(string url, string Data, Encoding Encode, RequestContentType reqtype = RequestContentType.Json) { string ret = ""; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.ProtocolVersion = HttpVersion.Version10; req.Method = "POST"; //req.Timeout = 5 * 60 * 1000; req.ContentType = requestTypeString(reqtype); // "application/json";// "application/x-www-form-urlencoded"; req.UserAgent = DefaultUserAgent; try { byte[] byteArray = Encode.GetBytes(Data); using (Stream newStream = req.GetRequestStream())//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面 { newStream.Write(byteArray, 0, byteArray.Length); newStream.Flush(); } using (WebResponse wr = req.GetResponse()) { Stream rs = wr.GetResponseStream(); ret = new StreamReader(rs, Encode).ReadToEnd(); wr.Close(); } //newStream.Close(); } catch (Exception ce) { return(ce.Message); //throw ce; } return(ret); }
/// <summary> /// 发送post请求 /// </summary> /// <param name="url">地址</param> /// <param name="paras">参数</param> /// <param name="headers">请求包头</param> /// <param name="contentType">请求内容格式</param> /// <param name="accept">接收内容格式</param> /// <returns></returns> public static string Post(string url, string paras, Dictionary<string, string> headers, RequestContentType? contentType, AcceptType? accept) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = HttpMethodType.Post.GetDescription(); request.ContentType = RequestContentType.UrlEncoded.GetDescription(); request.Accept = AcceptType.json.GetDescription(); if (headers != null) { foreach (KeyValuePair<string, string> kv in headers) { request.Headers.Add(kv.Key, kv.Value); } } if (contentType != null) request.ContentType = contentType.GetDescription(); if (accept != null) request.Accept = accept.GetDescription(); byte[] bs = Encoding.UTF8.GetBytes(paras); using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bs, 0, bs.Length); } try { using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } catch (WebException ex) { LogHelper.ErrorLog(ex); return null; } }
/// <summary> /// Initializes a new instance of the <see cref="RequestDetails"/> class. /// </summary> /// <param name="req"><see cref="HttpRequest"/> instance.</param> /// <param name="source">SOurce name for this request.</param> public RequestDetails(HttpRequest req, string source) { Source = source ?? "(Unknown)"; bool clearCache; bool.TryParse(req.Query["clearCache"], out clearCache); ClearCache = clearCache; // Get enableTrace QueryString value bool enableTrace; bool.TryParse(req.Query["enableTrace"], out enableTrace); EnableTrace = enableTrace; bool encodeBody = true; bool.TryParse(req.Query["encodeBody"], out encodeBody); EncodeBody = encodeBody; // Get MessageBody RequestBody = null; try { RequestBody = req.ReadAsStringAsync().GetAwaiter().GetResult(); } catch { } // Get Request ContentType RequestContentType = req.ContentType; // Get the Request body as a JSON object RequestBodyAsJson = null; IsFault = false; if ((RequestContentType?.ToLower()?.Contains("/json") == true) || (RequestContentType?.ToLower()?.Contains("+json") == true)) { // Attempt to parse the content as JSON try { RequestBodyAsJson = JToken.Parse(RequestBody); // if th e body is a JSON Object, check if it's a fault if (RequestBodyAsJson is JObject) { // Get the IsFault value IsFault = RequestBodyAsJson?["fault"]?["faultMessage"] != null; } } catch { } } // Get Request TransferEncoding RequestTransferEncoding = req.Headers.ContainsKey(HeaderConstants.TransferEncoding) ? req.Headers[HeaderConstants.TransferEncoding].ToString() : "none"; // Get Request ContentEncoding RequestContentEncoding = req.Headers.ContainsKey(HeaderConstants.ContentEncoding) ? req.Headers[HeaderConstants.ContentEncoding].ToString() : "none"; // Get Tracking Id - use the value from the envelope, else the value from the header, else create a new value string headerTrackingId = req.Headers.ContainsKey(HeaderConstants.AimTrackingId) ? req.Headers[HeaderConstants.AimTrackingId].ToString() : null; string envelopeTrackingId = (RequestBodyAsJson is JObject) ? RequestBodyAsJson?["header"]?["properties"]?["trackingId"]?.Value <string>() : null; TrackingId = new string[] { envelopeTrackingId, headerTrackingId, Guid.NewGuid().ToString() }.FirstOrDefault(s => !string.IsNullOrEmpty(s)); ApimInstanceName = Environment.GetEnvironmentVariable("ApimInstanceName"); ApimSubscriptionKey = Environment.GetEnvironmentVariable("ApimSubscriptionKey"); EnableOAuthForApim = (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EnableOAuthForAPIM")) && Environment.GetEnvironmentVariable("EnableOAuthForAPIM").ToLower() == "true"); EnableOAuthForLogicApps = (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EnableOAuthForLogicApps")) && Environment.GetEnvironmentVariable("EnableOAuthForLogicApps").ToLower() == "true"); EnableOAuthForManagementApi = (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EnableOAuthForManagementApi")) && Environment.GetEnvironmentVariable("EnableOAuthForManagementApi").ToLower() == "true"); }
public static Task <HttpResponse> PutAsync(string url, Stream content = null, RequestContentType contentType = RequestContentType.NotSpecified, string boundary = null, WebHeaderCollection headers = null, CookieCollection cookies = null, int?timeout = null, ICredentials credentials = null, RequestCachePolicy cachePolicy = null, X509Certificate2 clientCert = null, RemoteCertificateValidationCallback validateCallback = null) { return(Task.Run(() => Put(url, content, contentType, boundary, headers, cookies, timeout, credentials, cachePolicy, clientCert, validateCallback))); }
private async Task <HttpWebRequest> GetRequest_POSTAsync(HttpWebRequest request, RequestContentType content, RequestContentType accept, string post) { //Post in Byte kodieren byte[] data = new System.Text.UTF8Encoding().GetBytes(post); //Request anpassen request.Method = "POST"; switch (accept) { case RequestContentType.ALL: request.Accept = "*/*;"; break; case RequestContentType.JSON: request.Accept = "application / json; odata = verbose"; break; case RequestContentType.WWW_FORM: request.Accept = "application/x-www-form-urlencoded;"; break; case RequestContentType.XML: request.Accept = "text/xml;"; break; case RequestContentType.SOAP: request.Accept = "application/soap+xml;"; break; } switch (content) { case RequestContentType.JSON: request.ContentType = "application/json; odata=verbose"; break; case RequestContentType.WWW_FORM: request.ContentType = "application/x-www-form-urlencoded;"; break; case RequestContentType.XML: request.ContentType = "text/xml;"; break; case RequestContentType.SOAP: request.ContentType = "application/soap+xml;"; break; } request.ContentLength = data.Length; //POST-Stream einfügen if (string.IsNullOrEmpty(post)) { return(request); } try { Stream poststream = await request.GetRequestStreamAsync(); poststream.Write(data, 0, data.Length); poststream.Close(); return(request); } catch (Exception) { return(null); } }
private static async Task CreateAndSendMessageAsync(TcpClient client, object bodyValue, RequestType type, ResponseStatus status, RequestContentType contentType) { await client.GetStream().FlushAsync(); await SendClientMessage(client, new Request { Headers = new Dictionary <string, string> { { "Status", status.ToString() }, { "ContentType", contentType.ToString() } }, Body = $"{JsonConvert.SerializeObject(bodyValue)}", RequestType = type }); await client.GetStream().FlushAsync(); }