Home >Backend Development >C++ >How to Handle Multiple GET Methods in a Single ASP.NET Web API Controller?
Single Controller with Multiple GET Methods in ASP.NET Web API
Overcoming the error of multiple actions matching a request can be achieved through route definitions in WebApiConfig.
The provided solution advocates for using a combination of routes to support various GET methods and the standard REST methods:
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) });
To demonstrate this, consider the following test controller:
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) { } }
With the specified routes, this controller can handle the following requests:
GET /Test GET /Test/1 GET /Test/GetAll POST /Test PUT /Test/1 DELETE /Test/1
This solution ensures that even with multiple GET methods, the RESTful endpoints remain intact, providing flexibility and adherence to HTTP standards. Note that if your GET actions do not start with 'Get,' you can add the HttpGet attribute for clarity.
The above is the detailed content of How to Handle Multiple GET Methods in a Single ASP.NET Web API Controller?. For more information, please follow other related articles on the PHP Chinese website!