ASP.NET核心如何输出自定义XML模型

时间:2017-03-15 15:04:09

标签: c# xml asp.net-core formatting

我有一个用C#核心构建的Web API,我需要自定义我的一个端点提供的XML输出。

要配置我的应用程序以返回XML和JSON,我使用Accept Header,如下所示:

public class SageInvoice {

    public long Id { get; set; }

    public DateTime Created { get; set; }

    public long? CustomerId { get; set; }

    public long? JobId { get; set; }

    public DateTime Date { get; set; }

    public decimal Subtotal { get; set; }

    public decimal VAT { get; set; }

    public decimal Total { get; set; }
}

我有一个模型,我在控制器上返回:

<ArrayOfSageInvoice xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AutomotiveDTO.DTOs.SageIntegration">
    <SageInvoice>
        <Created>2017-03-15T11:09:34.21</Created>
        <CustomerId>1</CustomerId>
        <Date>2017-03-15T00:00:00</Date>
        <Id>2</Id>
        <JobId>1</JobId>
        <Subtotal>100.00</Subtotal>
        <Total>120.00</Total>
        <VAT>20.00</VAT>
    </SageInvoice>
    <SageInvoice>
        <Created>2017-03-15T11:11:26.853</Created>
        <CustomerId>2</CustomerId>
        <Date>2017-03-15T00:00:00</Date>
        <Id>3</Id>
        <JobId i:nil="true"/>
        <Subtotal>23532.00</Subtotal>
        <Total>28238.40</Total>
        <VAT>4706.40</VAT>
    </SageInvoice>
</ArrayOfSageInvoice>

XML就像这样:

<?xmlversion="1.0"encoding="utf-8"?>
<Order>
    <OrderSummary>
        <OrderID>1</OrderID>
        <OrderReference>ORDER1</OrderReference>
        <OrderDate>2017-03-15</OrderDate>
        <AccountNumber>ACCOUNT1</AccountNumber>
        <CompanyName>Company 1</CompanyName>
        <ContactTitle>Mr</ContactTitle>
        <ContactFirst>Dave</ContactFirst>
        <ContactLast>Dave</ContactLast>
        <Address1/>
        <Address2/>
        <Town/>
        <County/>
        <Postcode/>
        <Country/>
        <Telephone>01234567890</Telephone>
        <NumberOfItems>2</NumberOfItems>
        <OrderValue>200</OrderValue>
        <Downloaded>false</Downloaded>
    </OrderSummary>
    <OrderSummary>
    ...
    </OrderSummary>
</Order>

我的终端的消费者并不喜欢这样的结构,并希望我让它看起来更多:

[\w_]+@temp

如何在不破坏Accept标头JSON + XML输入/输出功能的情况下更改我的XML输出以匹配上述内容?

1 个答案:

答案 0 :(得分:1)

这应该这样做(见MSDN)。这些文档适用于.NET Framework,但也适用于.NET Core。

[CollectionDataContract(Name = "Invoice", ItemName = "InvoiceSummary")]
public class SageInvoice
{
    ...
}