【发布时间】:2022-01-26 00:03:16
【问题描述】:
我需要从我的 API 以不同格式返回数据。我正在使用标准格式化程序和一些自定义格式化程序。当我尝试像这样转换数据时一切正常:
[HttpPost]
public IActionResult Post(MyEntity entity)
{
return Ok(entity);
}
问题是,当我尝试对文件执行相同操作时,我无法正确格式化内容。
[HttpPost]
public async Task<IActionResult> Post()
{
var file = Request.Form.Files.Count > 0 ? Request.Form.Files[0] : null;
if (file == null)
return BadRequest();
var stream = file.OpenReadStream();
using var reader = new StreamReader(stream);
string content = await reader.ReadToEndAsync();
Request.ContentType.Remove(0);
Request.ContentType = file.ContentType;
return Ok(content);
}
有什么办法可以解决吗?我想我应该以某种方式手动使用格式化程序,但无法弄清楚。我也尝试过覆盖 Ok 方法,但 OkObjectResult 上的格式化程序是空的。
输入文件test.json:
{
"attr1": "hi",
"attr2": "there",
}
预期输出为 xml:
<MyEntity xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Application.Models">
<Attr1>hi</Attr2>
<Attr2>there</Attr2>
</MyEntity>
收到的输出:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{
"attr1": "hi",
"attr2": "there"
}</string>
【问题讨论】:
-
首先:您似乎认为可以通过为请求对象分配不同的内容类型指示符来自动更改实际内容类型。它确实不那样工作。
-
您能否向我们展示一个返回的示例、错误原因以及您期望的示例。
-
BTW:通常的做法是调用第二个 sn-p 的方法“PostAsync”。
-
如果您想例如将 XML 更改为 JSON,您需要实际更改内容格式。所以你需要某种数据反序列化/序列化。仅更改“内容为 XY”的字符串是不够的。
-
恐怕不会(至少我知道)。您需要明确地执行此操作。
标签: c# asp.net-core asp.net-web-api