Search code examples
c#asp.net-web-apiasp.net-web-api2asp.net-web-api-routing

Is it OK for multiple REST API methods to share same controller class?


Is it best practice to put each distinct Get method in its own controller class, or is it perfectly fine to have multiple (related and non-related) API methods in the same class, if the methods are very simple and uncomplicated.

E.g. these two API methods work fine in the same controller class, but would they be better off in their own class?

If so why?

public class TestController : ApiController
{
    [HttpGet]
    [Route("api/test/ping")]
    public IHttpActionResult Ping()
    {
        try
        {
            return Ok("HELLO");
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

    [HttpGet]
    [Route("api/test/echo/{message}")]
    public IHttpActionResult Echo(string message)
    {
        try
        {
            return Ok(message);
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.InternalServerError, ex.Message);
        }
    }
}

Solution

  • There is nothing stopping you from having multiple actions in a controller once their routes are distinct and do not cause route conflicts in the current or other controllers.

    Take your provided example. You can take advantage of route prefixes for the controller to help with the organizing of similar routes

    [RoutePrefix("api/test")]    
    public class TestController : ApiController {
    
        //GET api/test/ping
        [HttpGet] [Route("ping")]
        public IHttpActionResult Ping() {
            return Ok("HELLO");
        }
    
        //GET api/test/echo/hello%20world
        [HttpGet] [Route("echo/{message}")]
        public IHttpActionResult Echo(string message) {
            if(message == null)
                return BadRequest();
            return Ok(message);
        }
    }