API控制器的通用ActionResult返回类型

时间:2018-12-04 14:42:01

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

我有以下int main() { auto foo = std::make_unique<Foo>(); auto p_foo = foo.get(); while (/* condition */) { auto cbaz = std::make_shared<ConcreteBaz>(); auto p_cbaz = std::weak_ptr<ConcreteBaz> {cbaz}; // Scene gets a && via std::move here p_foo->acquire(p_cbaz.lock()); // this instantly gets converted to a shared_ptr EDIT: BUT IT DOESN'T INCREASE THE USE COUNT // do physical things to cbaz p_foo->release(/* actually takes a place to release into */); // do other physical things, then acquire cbaz again p_foo->acquire(p_cbaz.lock()); // this instantly gets converted to a shared_ptr and would be nullptr had I moved in the first acquire call EDIT: BUT IT DOESN'T INCREASE THE USE COUNT // do physical things to cbaz p_foo->release(/* actually takes a place to release into */); } } 方法用例。

良好路径:返回类型为@GetMapping("/user/getCount") public List<User> getCount(Model model){ return getUsers(model).size() } 的产品数组

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

(出于这篇文章的目的,下面的GetProducts()是我自己的标记)

Product[]

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

2 个答案:

答案 0 :(得分:4)

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

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

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

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

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

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

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

答案 1 :(得分:0)

您可以根据需要返回ActionResult<Product[]>。 但是对于错误情况,您可以使用StatusCode()帮助方法来返回错误消息,如下所示:

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