ASP.NET Web API 中具有多個GET 方法的單一控制器
可以透過路由來克服多個操作來匹配一個請求的錯誤WebApiConfig 中的定義。
提供的解決方案提倡使用路由組合來支援各種GET 方法和標準REST 方法:
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" }); routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}"); routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }); routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
為了示範這一點,請考慮以下測試控制器:
public class TestController : ApiController { public string Get() { return string.Empty; } public string Get(int id) { return string.Empty; } public string GetAll() { return string.Empty; } [HttpPost] public void Post([FromBody] string value) { } [HttpPut] public void Put(int id, [FromBody] string value) { } [HttpDelete] public void Delete(int id) { } }
使用指定的路由,此控制器可以處理以下請求:
GET /Test GET /Test/1 GET /Test/GetAll POST /Test PUT /Test/1 DELETE /Test/1
此解決方案確保即使使用多個 GET 方法,RESTful 端點也保持完整,提供靈活性並遵守 HTTP 標準。請注意,如果您的 GET 操作不以「Get」開頭,您可以新增 HttpGet 屬性以確保清晰。
以上是如何在單一 ASP.NET Web API 控制器中處理多個 GET 方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!