What is the "correct" way to have a call to a Web API REST service that simply returns a single integer?
I have no requirements here in terms of XML, JSON, or anything else. The call to the service just needs to return an integer.
Do I use the ResponseType
attribute here?
I have the service return type as HttpResponseMessage
, and for services such as something returning JSON I would set the Content property on this to StringContent
with UTF8 "application/json".
But what is correct for a single integer?
I recommend that you use the IHttpActionResult type for your API methods. It will allow you to use several different convenience methods for returning common responses. In your case it would just look like this:
public IHttpActionResult GetInteger() {
// Ok is a convenience method for returning a 200 Ok response
return Ok(1);
}
or if you wanted to return it wrapped in an object for easier JSON consumption an anonymous object is fine:
public IHttpActionResult GetInteger() {
// Ok is a convenience method for returning a 200 Ok response
return Ok(new {
value = 1
});
}
Documentation here
Summarized from the docs are some of the reasons why you would use IHttpActionResult:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With