Web API 2:Action的返回类型

Web API控制器中的Action方法有如下几种返回类型:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. 其它类型

基于上面几种不同的返回类型,Web API创建HTTP响应消息的机制也不同。

返回类型 Web API创建HTTP响应消息的机制
void 返回HTTP状态码204(无内容)
HttpResponseMessage 直接转换成HTTP响应消息
IHttpActionResult 调用接口的ExecuteAsync方法创建一个HttpResponseMessage对象,然后转换成HTTP响应消息
其它类型 把序列化后的返回值写入响应正文,并且返回HTTP状态码200(OK)
下面详细介绍几种返回类型

void

如果返回类型是void, Web API 会返回一个HTTP状态码204(无内容)的空HTTP响应消息
示例代码:
    public class ReturnValueDemoController : ApiController
{
//返回类型为void
public void Get()
{
}
}
HTTP响应消息:
HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 14:34:09 GMT

HttpResponseMessage

如果返回类型是HttpResponseMessage ,Web API直接把返回值转换成HTTP响应消息,HttpResponseMessage对象的属性对应响应消息的属性。你可以灵活的设置响应标头和响应正文,这就给了你对响应消息的更大的控制权。如下例:

 public class ReturnValueDemoController : ApiController
{
//返回类型为HttpResponseMessage
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode .OK, "hello");
response.Content = new StringContent ( "hello wep api", Encoding .Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan .FromSeconds(600)
};
return response;
}
响应:
HTTP/1.1 200 OK
Cache-Control: max-age=600
Content-Type: text/plain; charset=utf-16
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 15:14:05 GMT
Content-Length: 26 hello wep api
如果你给CreateResponse方法传入了一个领域模型, Web API就会把序列化后的领域模型写入响应正文。
示例:
    public HttpResponseMessage Get()
{
IQueryable <Product > products = repository.GetProducts();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode .OK, products);
return response;
}
响应:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 15:37:51 GMT
Content-Length: 264 [{"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":2,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":3,"Name":"洗发水","Description":null,"Price":20.0,"Category":"日用品"}]

IHttpActionResult

IHttpActionResult接口是在Web API 2才引入进来的,本质上,它定义了一个HttpResponseMessage工厂类。IHttpActionResult接口只定义了一个ExecuteAsync方法,该方法异步方式创建一个HttpResponseMessage实例。
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
如果控制器的Action返回类型是IHttpActionResult,Web API就会调用接口的ExecuteAsync方法创建一个HttpResponseMessage对象,然后转换成HTTP响应消息。以下是一个IHttpActionResult接口的实现,它创建了一个普通文本响应消息。

public class PlainTextResult : IHttpActionResult
{
private string text;
private HttpRequestMessage request; public PlainTextResult(string text, HttpRequestMessage request)
{
this .text = text;
this .request = request;
}
public Task < HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response=new HttpResponseMessage
{
Content = new StringContent (text, Encoding.Unicode),
RequestMessage = request
};
return Task .FromResult(response);
}
}
控制器Action代码:
//返回类型是IHttpActionResult
public IHttpActionResult Get()
{
return new PlainTextResult( "plain text result" ,Request);
}
响应:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-16
Expires: -1
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:17:30 GMT
Content-Length: 34 plain text result
通常情况下,你无须自己去实现IHttpActionResult接口, 在System.Web.Http.Results命名空间下已经包含了很多实现该接口的Action返回类型。ApiContoller类也定义了很多方法获取这些内置的Action返回类型。
在下面的例子里,如果没有找到某个产品,控制器调用ApiController.NotFound方法创建一个404 (Not Found)的响应消息。
HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w1?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:54:21 GMT
Content-Length: 0
如果找到了,控制器调用ApiController.OK方法创建一个HTTP状态码200(OK)响应正文是产品信息的响应消息。
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1wx?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:53:16 GMT
Content-Length: 82 {"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"}

其它返回类型

对于其它的返回类型,Web API会对返回值序列化,然后把序列化后的返回值写入到响应正文里,并且响应状态码是200(OK)。   
public IQueryable < Product> GetpProducts()
{
return repository.GetProducts();
}
响应:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w=?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 17:03:13 GMT
Content-Length: 264 [{"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":2,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":3,"Name":"洗发水","Description":null,"Price":20.0,"Category":"日用品"}]
使用这种返回类型的一个缺点就是你不能直接返回一个错误代码,例如404。不过,你可以通过抛出HttpResponseException异常来解决这个问题。
public Product GetProductById( int id)
{
Product product = repository.GetProductById(id);
if (product==null )
throw new HttpResponseException ( HttpStatusCode.NotFound); return product;
}
 
分类: WebAPI
标签: WebAPI

Web API 2:Action的返回类型的更多相关文章

  1. ASP.NET Web API 通过参数控制返回类型(JSON|XML)

    一个很实用的技巧,可以在访问web api服务的时候指定返回数据的格式类型,比如 json 或者 xml. 因为 web api 默认返回的是XML格式,但是现在json 比较流行,同时网上也有其他的 ...

  2. 通过Web API调用Action时各种类型输入参数传递值的方法

    本人微信公众号:微软动态CRM专家罗勇 ,回复280或者20180906可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . Dy ...

  3. 如何让ASP.NET Web API的Action方法在希望的Culture下执行

    在今天编辑推荐的<Hello Web API系列教程--Web API与国际化>一文中,作者通过自定义的HttpMessageHandler的方式根据请求的Accep-Language报头 ...

  4. Only one complex type allowed as argument to a web api controller action.

    错误内容: message":"An error has occurred.","exceptionMessage":"Only one c ...

  5. ASP.NET Web API 2:Action的返回类型

    Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 基于上面几种不同的返回类型,Web API ...

  6. Web API对application/json内容类型的CORS支持

    假设有一简单架构分为前后两部分,其一是Angular构成的前端页面站点,另一个则是通过ASP.NET Web API搭建的后端服务站点.两个站点因为分别布署,所有会有CORS(Cross-Origin ...

  7. ASP.NET Core Web API 控制器与方法返回输出

    DATA ACCESS LAYER 在一些不同的示例教程中,我们可能看到 DAL 的实现在主项目中,并且每个控制器中都有实例.我们不建议这么做. 当我们编写 DAL 时,我们应该将其作为一个独立的服务 ...

  8. ASP.NET Web API 如何通过程序控制返回xml还是json

    雖然 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式,並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式,不過有時候我們的確也需要讓程式來控制要回應哪種格式, ...

  9. Web api Json 接受的参数类型为父类,自动序列化为子类的过程

    场景: public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// t ...

随机推荐

  1. cocos2d-x 3.1.1 学习笔记[21]cocos2d-x 创建过程

    文章出自于  http://blog.csdn.net/zhouyunxuan RootViewController.h #import <UIKit/UIKit.h> @interfac ...

  2. UVA 1291 Dance Dance Revolution(DP)

    意甲冠军:跳舞机有一个上5积分,分别central, top, bottom, left, right分,区区足站立还是需要1点物理,从一个单纯的脚central点上须要2点体力,从一个点上移动到相邻 ...

  3. js中推断对象详细类型

    大家可能知道js中推断对象类型能够用typeof来推断. 看以下的情况 <script> alert(typeof 1);//number alert(typeof "2&quo ...

  4. Hybrid app 发展历程

    距离上一篇<基于微信 js-sdk 的简单应用>已经快一年了,说来真是惭愧.上次不久之后便换了工作,一直处于比较忙的状态.其次后面酣畅一段时间都没有从事移动相关的工作.直到今年3月份开始, ...

  5. jQuery EasyUI实现全部关闭tabs

    有时,当我们打开很多tabs当标签,要关闭一个接一个,它只能被关停 显然太麻烦,能够在选项卡的最右边加入一个button 实现关闭所有. 代码例如以下: <!DOCTYPE HTML PUBLI ...

  6. jqm的多列布局demo,html5的多列布局demo,多列布局的具体解说,html5开发实例具体解释

    因为移动设备屏幕宽度较小,所以一般不建议使用多列布局.但有时你可能须要并排放置一些元素(如button之类的). jQuery Mobile通过约定的类名ui-grid来提供了一种基于css的多列布局 ...

  7. Struts2 + uploadify 多文件上传完整的例子!

    首先,我这里使用的是  Jquery  Uploadify3.2版本号  导入相关的CSS  JS    <link rel="stylesheet" type=" ...

  8. rabbitmq的java简单的实现

    1,安装rabbitmq.我的是ubuntu14.04,在官网上面下载最新的安装文件http://www.rabbitmq.com/install-debian.html 2.安装完之后  启动rab ...

  9. 开玩笑html5(五岁以下儿童)---绕地球月球,地球绕太阳运动(canvas实现,同样可以移动哦)

    请珍惜劳动小编成果,这篇文章是原来小编,转载请注明出处. 速度的參数与真实速度有点差距.大家能够自行调整 <!DOCTYPE html> <html> <head> ...

  10. 使用cocoapods install友盟时报错Error installing UMengAnalytics

    报错: [!] /usr/bin/unzip /Users/soindy/Documents/SmartThermo/ios/SmartThermo/Pods/UMengAnalytics/file. ...