예제 #1
0
파일: RestClient.cs 프로젝트: ashic/Hermes
        static public HttpContent SerializeToContent <T>(this T from, RestClient.SerializationType serializationType)
        {
            HttpContent content;

            if (from == null)
            {
                content = new StringContent("", Encoding.ASCII, "application/xml");
            }

            else if (typeof(Stream).IsAssignableFrom(typeof(T)))
            {
                content = new StreamContent(from as Stream);
            }

            else
            {
                using (var stream = new MemoryStream())
                {
                    switch (serializationType)
                    {
                    case RestClient.SerializationType.Xml:
                        var xmlSettings = new XmlWriterSettings {
                            OmitXmlDeclaration = true
                        };
                        var xmlWriter = XmlWriter.Create(stream, xmlSettings);

                        var ns = new XmlSerializerNamespaces();
                        ns.Add("", "http://schemas.datacontract.org/2004/07/EB.PayDirect.Hermes.Core.Facade");

                        var xmlSerializer = new XmlSerializer(typeof(T));
                        xmlSerializer.Serialize(xmlWriter, from, ns);
                        break;

                    case RestClient.SerializationType.Json:
                        JsonSerializer.Serialize(from, stream);
                        break;
                    }
                    ;

                    var length = stream.Length;
                    stream.Seek(0, SeekOrigin.Begin);

                    content = new StreamContent(stream);
                    switch (serializationType)
                    {
                    case RestClient.SerializationType.Xml:
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
                        break;

                    case RestClient.SerializationType.Json:
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        break;
                    }
                    content.LoadIntoBuffer();
                }
            }
            return(content);
        }