英文:
Setting the API to accept XML for output format
问题
我想看看是否可以让我的 `API` 返回 `"XML"`,所以我将 `Accept Header` 更改为如下图片所示:
[![在此输入图片描述](https://i.stack.imgur.com/VlsCi.png)](https://i.stack.imgur.com/VlsCi.png)
然后我更新了我的代码如下。但仍然返回 `JSON`:为什么呢?
builder.Services.AddControllers(options =>
{
options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();
我在跟随一个 PluralSight 课程,他做了这个并且对他有效。
英文:
I wanted to see if I can havew my API
return "XML"
so I changed the Accept Header
to XML like this pic below :
And I updated my code like this below. But still it returns JSON
: Why?
builder.Services.AddControllers(options =>
{
options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();
I was following a PluralSight course that was doing this and worked for him.
答案1
得分: 1
根据您的描述以及共享的代码片段,我已尝试模拟您的问题,并且它按预期工作。此外,我可以从标头值中切换到XML和JSON响应。
您可以参考以下示例:
演示模型:
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
演示控制器:
[Route("api/[controller]")]
[ApiController]
public class CityXMLController : ControllerBase
{
public IActionResult GetCity()
{
var cityList = new List<City>()
{
new City { Id = 101, Name = "Alberta" },
new City { Id = 102, Name = "Toronto" },
new City { Id = 103, Name = "British Comlombia" },
};
return Ok(cityList);
}
}
**注意:**请确保在处理动态请求标头(XML和JSON)时使用Ok作为返回类型,因为特定的返回类型会根据标头值失败于相反的响应类型。
Program.cs:
builder.Services.AddControllers(options =>
{
options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();
输出:
**注意:**如果您想要了解有关Accept标头配置的更多详细信息,您可以在此处查看我们的官方文档。
英文:
> And I updated my code like this below. But still it returns JSON :
> Why?
According to your description and shared snippet I have tired to simulate your issue and its working as expected. In addition, I can switch between XML and Json response from the header value.
You can refer to following sample:
Demo Model:
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
Demo Controller:
[Route("api/[controller]")]
[ApiController]
public class CityXMLController : ControllerBase
{
public IActionResult GetCity()
{
var cityList = new List<City>()
{
new City { Id = 101, Name = "Alberta" },
new City { Id = 102, Name = "Toronto" },
new City { Id = 103, Name = "British Comlombia" },
};
return Ok(cityList);
}
}
Note: Please make sure you are using Ok as return type in order to handle dynamic request header both (XML and Json) because, specific return type would fail opposite response type as per header value.
Program.cs:
builder.Services.AddControllers(options =>
{
options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();
Output:
Note: If you would like to know more details on Accept header configuration you could check our official document here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论