C# ASP.NET WebAPI 中控制器操作的各种返回类型有哪些?

csharpserver side programmingprogramming更新于 2025/10/1 22:07:17

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){
         //某些操作
      }
   }
}

返回类型为 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");
         }
      }
   }
}

在上面的例子中,我们可以看到响应是自定义的。由于发送给 action 方法的 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);
      }
   }
}


相关文章