Home > Backend Development > C++ > How to Handle Multiple GET Methods in a Single ASP.NET Web API Controller?

How to Handle Multiple GET Methods in a Single ASP.NET Web API Controller?

Patricia Arquette
Release: 2025-01-05 09:43:08
Original
463 people have browsed it

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) });
Copy after login

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)
    {
    }
}
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template