如何说服Refit不要添加xml前导?

时间:2019-03-27 14:44:53

标签: c# httpwebrequest refit

我是使用Refit的新手。我现在正在使用Refit来调用需要xml作为输入的REST Api。这行得通,但是Refit似乎自动添加了众所周知的xml前导码来描述编码。

我想发送不带前导码的xml元素(根据目标系统的要求)。我该怎么做呢?这是我在启动类中的代码:

    var settings = new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    };
    services.AddRefitClient<IItemApi>(settings)
        .ConfigureHttpClient(c => c.BaseAddress = new Uri("http://127.0.0.1:5000"));

这是我的数据类,只是使用过的接口

public class PayLoad
{
    public string A { get; set; }
    public string B { get; set; }
}

public interface IItemApi
{
    [Post("/target/{id}")]
    Task<ApiResponse<string>> PostItemAsync(string id, [Body] PayLoad item,
        CancellationToken cancellationToken = default);
}

以下是帖子通话的示例:

        var result = itemApi.PostItemAsync("X",new PayLoad
        {
            A = "A",
            B = "B"
        });

这是原始请求:

POST http://127.0.0.1:5000/target/X HTTP/1.1
Content-Type: application/xml; charset=utf-8
Content-Length: 76
Host: 127.0.0.1:5000

<?xml version="1.0" encoding="utf-8"?><PayLoad><A>A</A><B>B</B></PayLoad>

如何以这种方式更改代码

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

不再在请求中了吗?

1 个答案:

答案 0 :(得分:0)

您需要配置xml序列化程序以使其跳过,因此您需要将示例中的设置更改为:

var settings = new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer(
            new XmlContentSerializerSettings
            {
                XmlReaderWriterSettings = new XmlReaderWriterSettings
                {
                    WriterSettings = new XmlWriterSettings
                    {
                        OmitXmlDeclaration = true
                    }
                }
            })
    };