单整数的Web API ResponseType [英] Web API ResponseType for Single Integer

查看:95
本文介绍了单整数的Web API ResponseType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the "correct" way to have a call to a Web API REST service that simply returns a single integer?

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

I have no requirements here in terms of XML, JSON, or anything else. The call to the service just needs to return an integer.

我在这里使用ResponseType属性吗?

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

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".

但是单个整数正确吗?

推荐答案

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

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);
}

或者如果您想将其包装在一个对象中以更方便地使用JSON来返回,则可以使用一个匿名对象:

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
   });
}

此处的文档

文档中总结了使用IHttpActionResult的一些原因:

Summarized from the docs are some of the reasons why you would use IHttpActionResult:

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

这篇关于单整数的Web API ResponseType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆