首页 > 解决方案 > 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)。反正有没有干净地支持也返回视图?

标签: c#asp.netasp.net-core

解决方案


你不能在同一个动作中同时做这两个。但是,您可以将通用功能分解为私有方法,然后以最少的代码重复实现两个操作:

[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 生成等目的。


推荐阅读