API控制器的通用ActionResult返回类型 [英] Generic ActionResult return type for API Controller

查看:226
本文介绍了API控制器的通用ActionResult返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于GetProducts()方法,我有以下用例.

I have the following use case for the GetProducts() method.

良好路径:返回产品类型为Product[]

Good path: Returns array of type product: Product[]

路径错误:返回状态码500和描述性字符串错误消息.

Bad path: Returns status code of 500 and descriptive string error message.

(出于这篇文章的目的,下面的<?Type?>是我自己的标记)

(<?Type?> below is my own markup for the purposes of this post)

[Route("api/[controller]/[action]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public ActionResult<?Type?> GetProducts()
    {
        try
        {
            Product[] products = DataAccess.GetProductsFromDb();
            return products;
        }
        catch 
        {
            Response.StatusCode = 400;
            return "Error retrieving products list"
        }
    }
}

有没有一种方法可以声明通用类型或两种类型的操作结果,以便它可以正常工作?

Is there a way I can declare an action result of a generic type or perhaps two types so that this can work?

推荐答案

您将返回IActionResult.我强烈建议制作也异步. 您可以通过控制器方法返回任何内容:

You would return an IActionResult. I highly recommend making is async as well. Here's how you can return anything through a controller method:

[Route("api/{controller}")]
public class ProductsController : Controller
{
    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        var products = await DataAccess.GetProductsFromDb();
        if (products is null)
        {
            return Ok(products);
        }
        else
        {
            return NotFound("Item not found!");
        }
    }
}

请注意,OkNotFoundController抽象类中的方法,它使您可以返回所需的任何对象,或者根本不返回任何对象.

Note the Ok and NotFound are methods in the Controller abstract class which allows you to return any object you want, or no object at all.

我强烈建议您在继续使用.net core之前,快速浏览一下Visual Studio中的示例项目模板,或者如果您正在另一个IDE中进行开发,请在终端中运行dotnet new mvc.

I highly recommend before continuing using .net core you take a quick look at the example project template in Visual Studio, or if you're developing in another IDE run dotnet new mvc in your terminal.

如果要处理异常,则应在最低级别上进行处理.假设GetProductsFromDb()是最低级别,并且您没有服务层(您会后悔在生产中使用此设计!),您可以尝试/捕获.

If you want to handle an exception you should handle it on the lowest level. Assuming GetProductsFromDb() is the lowest level and you have no service layer (you'll regret this design choice in production!) you would put a try/catch.

[Route("api/{controller}")]
public class ProductsController : Controller
{
    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        Products[] products;
        try
        {
            products = await DataAccess.GetProductsFromDb();
        }
        catch(Exception e)
        {
            Log.Error(e, "Unable to receive products");
            return InternalServerError("Unable to retrieve products, please try again later");
        }
        if (!products.Any())
        {
            return NotFound("No products were found");
        }
        else
        {
            return Ok(products);
        }
    }
}

在大多数情况下,速度并不比稳定性重要,当然在现阶段还不是.在如此高的层次上,捕获异常的代价微不足道.

Speed is NOT more important than stability in most cases, and certainly not at this stage of development. the cost of catching an exception is insignificant on something so high-level.

这篇关于API控制器的通用ActionResult返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆