我有一個以C#爲核心構建的Web API,我需要自定義其中一個端點提供的XML輸出。ASP.NET核心如何輸出自定義XML模型
配置我的應用程序返回XML和JSON,我用Accept頭,像這樣:
// Add framework services.
services
.AddMvc(options => {
options.RespectBrowserAcceptHeader = true;
})
//support application/xml
.AddXmlDataContractSerializerFormatters()
//support application/json
.AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
而且我有一個模型,我在控制器上返回:
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; }
}
的XML出來像這樣:
<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>
我的端點的消費者不喜歡它這樣的結構,並希望我做廁所ķ更多:
<?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></Telephone>
<NumberOfItems>2</NumberOfItems>
<OrderValue>200</OrderValue>
<Downloaded>false</Downloaded>
</OrderSummary>
<OrderSummary>
...
</OrderSummary>
</Order>
我怎樣才能改變我的XML輸出相匹配的上述不破壞的接受報頭JSON + XML輸入/輸出功能?
您可以用'[XML ...屬性約]'更改標籤的名稱雖然'' 將ofcourse仍然丟失或者你應該把它添加到您的類。 –
我已經削減了很多代碼,試圖簡化它的tbf隊友,但是謝謝如果Tseng的回答不起作用,我會嘗試一下 – Smithy
@JoelHarkes訪問[Xml]隊友需要什麼軟件包? – Smithy