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. innerHTML使用方法

    使用方法: 比方在<body>中写了例如以下的代码:<div id=top></div> 如今用top.innerHTML="..........&quo ...

  2. 使用API创建AR 贷项通知单

    DECLARE --8000000063 l_dummy varchar2(240); l_customer_trx_id ra_customer_trx.customer_trx_id%type; ...

  3. android tips—NumberPicker,DataPicker,TimePicker样式改动

    在使用NumberPicker.DataPicker,TimePicker这几个控件时,非常easy出现例如以下这个界面 可是我们想要的却是以下图示的结果 改动Application.activity ...

  4. 【Spark亚太研究院系列】Spark道路的真正的主人-第一章 构建Spark星团(第五步)(6)

    结束historyserver例如,下面的命令可以看到: 第四步:验证Hadoop分布式集群 首先在hdfs文件系统上创建两个文件夹.创建步骤例如以下所看到的: watermark/2/text/aH ...

  5. windows 10 install oracle 12c error:[ INS-30131 ]

    "[ INS-30131 ] the Initial Setup That Is Required to Run the Installation Program Validation Wa ...

  6. 博客搬到了http://xianglong.me

    自己用Django建立个人博客.这个博客的部分已经迁移到新的个人博客. 博客地址:龙 (http://xianglong.me),欢迎. 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  7. YouTube图片幻灯片分享技巧

    以前,您将使用的Windows Movie Maker或Picasa的工具,如缝合的图像文件转换成视频上传到YouTube.然而,添美的小编分享了她的技巧,你可以创建一个图片直接进入YouTube的视 ...

  8. .NET应用架构设计—四色原型模式(色彩造型、域无关的模型)(概念版)

    阅读文件夹: 1.背景介绍 2.问自己,UML对你来说有意义吗?它帮助过你对系统进行分析.建模吗? 3.一直以来事实上我们被一个缝隙隔开了,使我们对OOAD遥不可及 4.四色原型模式填补这个历史缝隙, ...

  9. POJ2299 Ultra-QuickSort 【树阵】+【hash】

    Ultra-QuickSort Time Limit: 7000MS   Memory Limit: 65536K Total Submissions: 39529   Accepted: 14250 ...

  10. Oracle 多行转多列

    Oracle 多行转多列,列值转为列名   前段时间做调查问卷,客户创建自定义问卷内容,包括题目和选项内容; 之后需要到处问卷明细,,,,麻烦来咯 于是到网上到处搜索,没有直接结果;于是又找各种相似的 ...