3

我正在使用ObjectContent这样构建 XML 请求:

private HttpRequestMessage CreateRequest<T>(T content, HttpMethod method) where T : class
{
    // create http message request
    var request = CreateRequest(method);

    // set contents of the HTTP message
    var xmlFormatter = new XmlMediaTypeFormatter
                           {
                               Indent = true,
                               UseXmlSerializer = true
                           };

    var objectContent = new ObjectContent<T>(content, xmlFormatter);
    request.Content = objectContent;

    // return HttpRequestMessage
    return request;
}

这很好用!但是,输出不包括 XML 序言,例如

<?xml version="1.0" encoding="UTF-8"?>

我怎样才能鼓励XmlSerializer包括该行?

4

2 回答 2

2

我不知道如何做到这一点,ObjectContent所以我先将它序列化,然后通过以下方式将其传递给请求StreamContent

private HttpRequestMessage CreateRequest<T>(T content, HttpMethod method) where T : class
{
    var request = CreateRequest(method);
    var encoding = Encoding.UTF8;
    var xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = encoding };

    // StringWriterWithEncoding courtesy of http://stackoverflow.com/a/9459212/29
    using (var stringWriter = new StringWriterWithEncoding(encoding))
    using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
    {
        var xmlSerializer = new XmlSerializer(typeof(T));
        xmlSerializer.Serialize(xmlWriter, content);
        request.Content = new StringContent(stringWriter.ToString(), encoding);
    }

    return request;
}
于 2013-08-08T17:18:47.193 回答
2

您的旧解决方案非常接近正确执行。

可以像这样更改覆盖类中设置的 OmitXmlDeclaration

    public class CustomXmlMediaTypeFormatter : XmlMediaTypeFormatter
    {
        public CustomXmlMediaTypeFormatter()
        {
            UseXmlSerializer = true;
            WriterSettings.OmitXmlDeclaration = false;
        }
    }

我也花了一段时间才弄清楚,但人们应该知道,只需将 WriterSettings 设置为不省略序言即可。

于 2016-05-25T13:40:40.170 回答