C#C
C#2y ago
qqdev

ASP.NET: Elegant controller <-> service interaction

Hey! I am looking for an elegant controller <-> service interaction.

Example (pseudocode):
[ApiController]
[Route("[controller]")]
public class CarController(ICarService carService) : ControllerBase
{
    public async Task<IActionResult> UpdateCar(CarDto carDto)
    {
        var (car, statusCode) = await carService.UpdateCar(carDto);
        
        if (statusCode != HttpStatusCode.OK)
        {
            return StatusCode((int)statusCode);
        }

        return Ok(car);
    }
}


My issue with this code: The service layer is returning an HTTP status code although the car service shouldn't have to do anything with HTTP stuff.
I thought about adding a dedicated enum which would kinda imitate some of the HTTP status codes (OK, NotFound, Conflict).

Other ideas:
  • Throw custom exceptions (don't like this one, exceptions are ugly)
Do you have a more convenient solution for this issue? How do you deal with this kind of stuff?

Thanks in advance!

Related:
Was this page helpful?