c# - Asp.net core 返回 View 或 Json/XML 的最干净方式
问题描述
在 asp.net 核心中,我想设置我的 API 控制器来执行以下操作:
默认return View(model);
/api/id.json 转为return model;
json
/api/id.xml 转为return model;
xml
后两个可以通过使用[FormatFilter]
see here来实现
[FormatFilter]
public class ProductsController
{
[Route("[controller]/[action]/{id}.{format?}")]
public Product GetById(int id)
但是,这需要该方法返回一个对象而不是 View(object)。反正有没有干净地支持也返回视图?
解决方案
你不能在同一个动作中同时做这两个。但是,您可以将通用功能分解为私有方法,然后以最少的代码重复实现两个操作:
[Route("[controller]")]
[FormatFilter]
public class ProductsController : Controller
{
private Product GetByIdCore(int id)
{
// common code here, return product
}
[HttpGet("[action]/{id}")]
[ActionName("GetById")]
public IActionResult GetByIdView(int id) => View(GetByIdCore(id));
[HttpGet("[action]/{id}.{format}")]
public Product GetById(int id) => GetByIdCore(id);
}
这里有必要使用不同的动作名称,因为方法签名不能仅仅在返回类型上有所不同。但是,[ActionName]
可以如上所述使用该属性以使它们看起来具有相同的名称,以用于 URL 生成等目的。
推荐阅读
- api - 使用 Blogger API 指定永久链接和帖子描述
- jquery - 新值被推送到 videoarr,但我的 html 没有显示新推送的数据。我可以做些什么来改进我的代码?
- javascript - 尝试为我的 chartjs 和 googlecharts 使用 axios、vuejs 和一个虚拟 api(仅获取请求)
- java - 如果一个数组在排序之前和排序之后,我如何检查是否相等
- arduino - ESP32 作为 WiFi 接入点在连接时崩溃
- python - 如何创建一个函数,以便它通过迭代主数据帧来创建数据帧
- node.js - 在 azure functionV2 中使用 node.js 更新实体
- angular - 按键排序对象,同时保留当前值以匹配数组顺序
- python - 错误类型错误:“列”对象在结构的 pyspark 数据帧中不可调用
- reactjs - 如何为特定数据附加嵌套状态?