单个整数的Web API ResponseType

Pat*_*ick 2 c# asp.net-web-api asp.net-web-api2

调用只返回单个整数的Web API REST服务的"正确"方法是什么?

我在这里没有XML,JSON或其他任何要求.对服务的调用只需要返回一个整数.

我在ResponseType这里使用该属性吗?

我有服务返回类型HttpResponseMessage,并且对于诸如返回JSON的东西之类的服务,我将StringContent使用UTF8"application/json" 将Content属性设置为.

但是对于单个整数来说什么是正确的?

Jes*_*ter 5

我建议您为API方法使用IHttpActionResult类型.它允许您使用几种不同的便捷方法来返回常见响应.在你的情况下,它看起来像这样:

public IHttpActionResult GetInteger() {
   // Ok is a convenience method for returning a 200 Ok response
   return Ok(1);
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想将它包装在一个对象中以便于JSON消费,那么匿名对象就可以了:

public IHttpActionResult GetInteger() {
   // Ok is a convenience method for returning a 200 Ok response
   return Ok(new {
      value = 1
   });
}
Run Code Online (Sandbox Code Playgroud)

文档在这里

从文档中总结出您使用IHttpActionResult的一些原因:

  • 简化控制器的单元测试.
  • 将用于创建HTTP响应的通用逻辑移动到单独的类中.
  • 通过隐藏构造响应的低级细节,使控制器操作的意图更加清晰.