Web API ResponseType for Single Integer

2019-07-18 03:43发布

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?

3条回答
beautiful°
2楼-- · 2019-07-18 03:56

You can implement your own content type deriving from HttpContent class, which is marked as abstract.

StringContent derives indirectly from it by inheriting from ByteArrayContent.

Generally it depends on the real "meaning" of your int. If this is some kind of an identifier, I'd wrap it into some kind of an object.

查看更多
【Aperson】
3楼-- · 2019-07-18 04:00

Well, depending on what you wanted to response body to look like. Just a number:

return Request.CreateResponse(HttpStatusCode.OK, "1");

A JSON object containing the number:

var myNumber = new
{
    theNumber = 1
};
return Request.CreateResponse(HttpStatusCode.OK, myNumber);
查看更多
来,给爷笑一个
4楼-- · 2019-07-18 04:11

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:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
查看更多
登录 后发表回答