C# ASP.NET Web API 中控制器操作的各种返回类型是什么?


Web API 操作方法可以具有以下返回类型。

  • Void

  • 基本类型/复杂类型

  • HttpResponseMessage

  • IHttpActionResult

Void

并非所有操作方法都必须返回某些内容。它可以具有 void 返回类型。

示例

using DemoWebApplication.Models
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public void Get([FromBody] Student student){
         //Some Operation
      }
   }
}

具有 void 返回类型的操作方法将返回204 No Content响应。

基本类型/复杂类型

操作方法可以返回基本类型,例如 int、string 或复杂类型,例如 List 等。

示例

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public List<string> Get([FromBody] Student student){
         return new List<string>{
            $"The Id of the Student is {student.Id}",
            $"The Name of the Student is {student.Name}"
         };
      }
   }
}

HttpResponseMessage

示例

当我们想要自定义操作方法的返回类型(操作结果)时,可以使用 HttpResponseMessage。通过向 HttpResponseMessage 提供状态代码、内容类型和要返回的数据来自定义响应。

using DemoWebApplication.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public HttpResponseMessage Get([FromBody] Student student){
         if(student.Id > 0){
            return Request.CreateResponse(HttpStatusCode.OK, $"The Sudent Id is
            {student.Id} and Name is {student.Name}");
         } else {
            return Request.CreateResponse(HttpStatusCode.BadRequest, $"InValid
            Student Id");
         }
      }
   }
}

在上面的示例中,我们可以看到响应是自定义的。由于发送到操作方法的 Id 为 0,因此执行 else 部分并返回 400 Bad request 和提供的错误消息。

IHttpActionResult

示例

IHttpActionResult 接口在 Web API 2 中引入。它本质上定义了一个 HttpResponseMessage 工厂。IHttpActionResult 位于 System.Web.Http 命名空间中。与 HttpResponseMessage 相比,使用 IHttpActionResult 的优点如下。

  • 简化了单元测试控制器。

  • 将创建 HTTP 响应的公共逻辑移动到单独的类中。

  • 通过隐藏构建响应的底层细节,使控制器操作的意图更清晰。

示例

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IHttpActionResult Get([FromBody] Student student){
         var result = new List<string>{
            $"The Id of the Student is {student.Id}",
            $"The Name of the Student is {student.Name}"
         };
         return Ok(result);
      }
   }
}

更新于:2020年8月19日

7K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.