Ally
Ally

Reputation: 4942

How to handle status codes with .NET web API?

I'm new to the .NET web api. But I can't figure out what the best practice should be when returning status codes. I've followed the tutorial on creating a web api that supports crud operations to get a good idea on how it all works.

I have a spec where the response to every request returns a status code along with other data, I can change the spec if need be but I can't work out if it's good to return a status code and also return all the data requested or to just return the data on it's own.

For example if I made a request to GetAllCarManufacturers without being authenticated I'd return a custom statusCode of 1 (Indicating not authenticated), and message "User is not authenticated.". But if I was authenticated I'd like to send back a statusCode of 0 (indicating success) and all the car manufacturers. This seems to go against the way the tutorial is organised as only the car manufacturers are sent back without any additional data. Which leads me to believe passing around a statusCode isn't the correct thing to do.

I've seen in the example crud demo that HttpResponseExceptions are thrown which sets the HttpStatusCode to a certain value (see code below). Should I be using that instead of returning my own status code? But then my concern is it doesn't have enough different status codes that will match my custom scenarios.

// Setting the HTTPStatusCode example.
throw new HttpResponseException(HttpStatusCode.NotFound);

Upvotes: 0

Views: 871

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

.NET Web API sets up a convention for HTTP calls to a server that supports a REST interface. So, if you follow the convention, you should return HTTP Status Codes as a way of indicating what happened to the request when the server processed it.

HTTP Status Codes are part of the HTTP spec and can be found here.

There are many benefits to using HTTP Status Codes. One is that the HTTP Status Code is a header, so the client doesn't have to look into the content of the response in order to find out what happened.

So, returning a custom status code (of say 0 or 1) is not very useful to HTTP clients if they expect a RESTful experience from your interface.

Upvotes: 1

Related Questions