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);
}
}
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP