PortableRest.RestRequest.GetRequestBody C# (CSharp) Method

GetRequestBody() private method

private GetRequestBody ( ) : string
return string
        internal string GetRequestBody()
        {
            switch (ContentType)
            {
                case ContentTypes.FormUrlEncoded:
                    var parameters = Parameters.Aggregate(new StringBuilder(),
                        (current, next) =>
                            current.Append(string.Format("{0}{1}={2}", current.Length > 0 ? "&" : "",
                                Uri.EscapeDataString(next.Key),
                                next.GetEncodedValue())));
                    return parameters.ToString();
                //case ContentTypes.MultiPartFormData:
                case ContentTypes.Xml:
                    var result = "";
                    if (Parameters.Count == 0) return result;

                    var type = Parameters[0].Value.GetType();

                    var serializer = new DataContractSerializer(type);
                    using (var stream = new MemoryStream())
                    {
                        serializer.WriteObject(stream, Parameters[0].Value);
                        result = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
                    }

                    if (IgnoreXmlAttributes || string.IsNullOrWhiteSpace(result)) return result;

                    var doc = XElement.Parse(result);
                    //Clean all of the DataContract namespaces from the payload.
                    doc.Attributes().Remove();
                    Transform(IgnoreRootElement ? doc.Descendants().First() : doc, Parameters[0].Value.GetType());
                    return doc.ToString();
                default:
                    switch (Parameters.Count)
                    {
                        case 0:
                            return "";
                        case 1:
                            return JsonConvert.SerializeObject(Parameters[0].Value, JsonSerializerSettings);
                        default:
                            var body = new JObject();
                            foreach (var parameter in Parameters)
                            {
                                body.Add(parameter.Key, new JObject(parameter.Value));
                            }
                            return JsonConvert.SerializeObject(body, JsonSerializerSettings);
                    }
            }
        }

Usage Example

Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="restRequest"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task <HttpResponseMessage> GetHttpResponseMessage <T>(RestRequest restRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            //RWM If we've specified a DateFormat for the Client, but not not the Request, pass it down.
            if (!string.IsNullOrWhiteSpace(DateFormat) && string.IsNullOrWhiteSpace(restRequest.DateFormat))
            {
                restRequest.DateFormat = DateFormat;
            }

            //RWM: If we've specified JsonSerializerSettings for the Client, but not not the Request, pass it down.
            if (JsonSerializerSettings != null && restRequest.JsonSerializerSettings == null)
            {
                restRequest.JsonSerializerSettings = JsonSerializerSettings;
            }

            //RWM: We've moved this call to inside the HttpHandler setter... let's see if that solves our Mono problems.
            //ConfigureHandler(HttpHandler);
            _client = new HttpClient(HttpHandler);

            if (string.IsNullOrWhiteSpace(UserAgent))
            {
                SetUserAgent <T>();
            }
            _client.DefaultRequestHeaders.Add("user-agent", UserAgent);

            var message = new HttpRequestMessage(restRequest.Method, restRequest.GetResourceUri(BaseUrl));

            //RWM: Add the global headers for all requests.
            foreach (var header in Headers)
            {
                message.Headers.Add(header.Key, header.Value);
            }

            //RWM: Add request-specific headers.
            foreach (var header in restRequest.Headers)
            {
                message.Headers.Add(header.Key, header.Value.ToString());
            }

            //RWM: Not sure if this is sufficient, or if HEAD supports a body, will need to check into the RFC.
            if (restRequest.Method != HttpMethod.Get && restRequest.Method != HttpMethod.Head && restRequest.Method != HttpMethod.Trace)
            {
                //RWM: This feels hacky. May need some tweaking.
                if (restRequest.ContentType == ContentTypes.ByteArray)
                {
                    //RWM: A fix for an issue uncovered by @scottisafool.
                    if (restRequest.Parameters.Count > 0)
                    {
                        message.Content = new ByteArrayContent(restRequest.Parameters[0].GetEncodedValue() as byte[]);
                    }
                }
                else
                {
                    var contentString = new StringContent(restRequest.GetRequestBody(), Encoding.UTF8, restRequest.GetContentType());
                    message.Content = contentString;
                }
            }

            return(await _client.SendAsync(message, cancellationToken).ConfigureAwait(false));
        }
All Usage Examples Of PortableRest.RestRequest::GetRequestBody