當這樣呼叫時,我想要后端的原始回應:
GET http://localhost:49610/docs/3085
Accept: application/xml
Authorization: Bearer {{jwtToken}}
將會:
<SolutionReportResponseDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Company.Common.NetStandard.Dtos">
<Metadata />
<Databases />
<Variables />
</SolutionReportResponseDto>
代替:
<SolutionReportResponseDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Company.Common.NetStandard.Dtos"><Metadata /><Databases /><Labels /><Variables /></SolutionReportResponseDto>
我設法用下一個代碼做到了這一點:
services.AddControllers().AddXmlDataContractSerializerFormatters();
services.Configure<MvcOptions>(options =>
{
XmlWriterSettings xmlWriterSettings = options.OutputFormatters
.OfType<XmlDataContractSerializerOutputFormatter>()
.Single()
.WriterSettings;
xmlWriterSettings.Indent = true;
});
有沒有更短的方法?所以我可以在 AddXmlDataContractSerializerFormatters() 方法中設定縮進嗎?也不確定如何使用 MvcXmlOptions?
public static IMvcBuilder AddXmlDataContractSerializerFormatters(this IMvcBuilder builder, Action<MvcXmlOptions> setupAction);
uj5u.com熱心網友回復:
我最終得到了這個:
services.AddControllers(options =>
{
// Works around IE 11's caching behavior for API calls
options.Filters.Add(new ResponseCacheAttribute { NoStore = true, Location = ResponseCacheLocation.None });
options.OutputFormatters.RemoveType<XmlDataContractSerializerOutputFormatter>();
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter(new XmlWriterSettings() { Indent = true }));
});
uj5u.com熱心網友回復:
您也可以在 .NET Core 6 中簡單地添加它
builder.Services.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
您將需要參考命名空間“ using Microsoft.AspNetCore.Mvc.Formatters;”
在 .NET 5 中
services.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
uj5u.com熱心網友回復:
MvcOptions 與 MvcXmlOptions 不同,您應該使用 AddControllersWithViews 方法來設定它,而不是使用 AddXmlDataContractSerializerFormatters。
更多細節,您可以參考以下代碼:
services.AddControllersWithViews( options => {
{
XmlWriterSettings xmlWriterSettings = options.OutputFormatters
.OfType<XmlDataContractSerializerOutputFormatter>()
.Single()
.WriterSettings;
xmlWriterSettings.Indent = true;
}
}).AddXmlDataContractSerializerFormatters() ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/513892.html
