ASP.NET Core 2.1中的ActionResult<T>
2024-10-16
11
ASP.NET Core 2.1的一个新功能是,一个名为ActionResult<T>的新类型,它允许您返回响应类型或任何操作结果,同时仍然指示响应类型。在这篇短文中,我们将看到如何使用ASP.NET Core 2.1中的新型ActionResult<T>,以及它解决了什么问题。
下面是一段非常熟悉的API操作代码。
public Product Get(int id)
{
Product prod = null;
// TODO: Get product by Id
return prod;
}
在这里,我们按ID搜索产品并返回搜索的产品。API操作方法的返回类型是产品,它有助于API文档以及客户机了解预期的响应。但是,这个代码有一个问题,因为当没有针对ID的产品时,这个代码将失败。修复也很简单。
public ActionResult Get(int id)
{
Product prod = GetProduct(id);
if(prod == null)
{
return NotFound();
}
return ok(prod);
}
很好,但是API操作方法签名现在不再指示返回对象的类型。ASP.NET Core 2.1中的新类型ActionResult<T>解决了这个问题。
在ASP.NET Core 2.1中,我们可以用以下方法使用ActionResult<T>编写上述代码。
public ActionResult<Product> Get(int id)
{
Product prod = GetProduct(id);
if(prod == null)
{
return NotFound();
}
return prod;
}
在这里,ActionResult将在运行时基于结果返回产品对象或ActionResult。
更新于:2天前赞一波!
相关文章
- .NET Core 3.0创建一个单独的可执行文件
- 在ASP.NET Core 2.1中使用HttpClientFactory的3种方法
- .NET Core MVC应用程序创建教程
- .NET Core中的File和PhysicalFile
- .NET Core 读取配置文件方法
- .NET Core 管道模型中间件及管道模拟实现
- ASP.NET Core多环境配置
- .NET Core 日志配置,NLog配置示例
- ASP.NET Core主机和应用启动流程
- .NET Core SkiaSharp替代System.Drawing的用法
- .NET Core 3.X路由中间件和终结点中间件
- .Net报错Could not find a part of the path bin\roslyn\csc.exe
- IIS中.NET Core报错HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
- .NET Core分部视图PartialView用法
- .NET Core 视图组件Component用法
- ASP.NET Core的三种部署方式
- .NET Core中使用System.Drawing处理图像
- .NET Core Razor Page ajax请求返回400 Bad request
- .NET Core上传文件报Access xxx.tmp is denied错误
- ASP.NET Core 使用Razor code blocks替代@helper
文章评论
评论问答