Search code examples
c#asp.net-web-api2http-status-codes

Passing HttpStatusCodes throughout different layers in web api application


I'm writing a web api app that I have divided into various projects such Web, Services, DataAccess - so basically the web api controller contacts the service layers which then can access the data access layer.

I was returning just a bool to let me know if the data access method has completed ok, then picking this up in the service layer and then back to the controller...where I can then respond with a HTTPStatusCode of 200, or 500 etc..depending whether or not the operation has returned a true or false.

Instead of bool is it good practice to use HttpStatusCodes instead...or should HTTP status codes only be used in the Controller - to return a response to the app that's calling the web api or should it be something else?

Thanks,


Solution

  • First of all classes should have the least possible knowledge of the world around them. Suppose you implement the repository pattern to fetch data. Your repository (data access layer) should not even know about HTTP, nor it should expect to be a part of web application. Its only concern is accessing a particular table.

    It’s difficult to suggest specific solution without understanding the big picture, but you may consider the following:

    1. Raise an exception if your application depends on data that couldn’t be fetched. It’ll propagate as 500 response.
    2. Use enum instead of bool to make code more readable.
    3. Create DataResponse class to incapsulate result of data access operation. You may then use the adapter pattern to adapt DataResponse to HttpResponse.