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  No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: 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()
};
return response;
}
响应:
HTTP/1.1  OK
Cache-Control: max-age=
Content-Type: text/plain; charset=utf-
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length: 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  OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-
Expires: -
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length: [{"ProductId":,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":,"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  OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-
Expires: -
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length: plain text result
通常情况下,你无须自己去实现IHttpActionResult接口, 在System.Web.Http.Results命名空间下已经包含了很多实现该接口的Action返回类型。ApiContoller类也定义了很多方法获取这些内置的Action返回类型。
在下面的例子里,如果没有找到某个产品,控制器调用ApiController.NotFound方法创建一个404 (Not Found)的响应消息。
HTTP/1.1  Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w1?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length:
如果找到了,控制器调用ApiController.OK方法创建一个HTTP状态码200(OK)响应正文是产品信息的响应消息。
HTTP/1.1  OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-
Expires: -
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1wx?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length: {"ProductId":,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"}

其它返回类型

对于其它的返回类型,Web API会对返回值序列化,然后把序列化后的返回值写入到响应正文里,并且响应状态码是200(OK)。   
public IQueryable < Product> GetpProducts()
{
return repository.GetProducts();
}
响应:
HTTP/1.1  OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-
Expires: -
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.
X-SourceFiles: =?UTF-?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w=?=
X-Powered-By: ASP.NET
Date: Wed, Mar :: GMT
Content-Length: [{"ProductId":,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":,"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;
}

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

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

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

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

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

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

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

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

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

  5. ASP.NET Web API默认支持的媒体类型(SupportedMediaTypes)

    JsonMediaTypeFormatter XmlMediaTypeFormatter ( application/xml  text/xml) FormUrlEncodedMediaTypeFor ...

  6. ASP.NET Web API 数据提供系统相关类型及其关系

  7. 【ASP.NET Web API教程】1.1 第一个ASP.NET Web API

    Your First ASP.NET Web API (C#)第一个ASP.NET Web API(C#) By Mike Wasson|January 21, 2012作者:Mike Wasson ...

  8. HttpActionDescriptor,ASP.NET Web API又一个重要的描述对象

    HttpActionDescriptor,ASP.NET Web API又一个重要的描述对象 通过前面对“HttpController的激活”的介绍我们已经知道了ASP.NET Web API通过Ht ...

  9. ASP.NET Web API 2中的错误处理

    前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...

  10. ASP.NET Web API 控制器创建过程(二)

    ASP.NET Web API 控制器创建过程(二) 前言 本来这篇随笔应该是在上周就该写出来发布的,由于身体跟不上节奏感冒发烧有心无力,这种天气感冒发烧生不如死,也真正的体会到了什么叫病来如山倒,病 ...

随机推荐

  1. P3007 [USACO11JAN]大陆议会The Continental Cowngress

    P3007 [USACO11JAN]大陆议会The Continental Cowngress 题意: 给出 n 个法案, m 头牛的意见, 每头牛有两个表决 格式为 "支持或反对某法案&q ...

  2. java基础-IO流对象之Properties集合

    java基础-IO流对象之Properties集合 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Properties集合的特点 Properties类表示了一个持久的属性集. ...

  3. Spring 手动提交事务

    在使用Spring声明式事务时,不需要手动的开启事务和关闭事务,但是对于一些场景则需要开发人员手动的提交事务,比如说一个操作中需要处理大量的数据库更改,可以将大量的数据库更改分批的提交,又比如一次事务 ...

  4. 6.redis的分布式锁

    https://www.cnblogs.com/linjiqin/p/8003838.html

  5. (CoreText框架)NSAttributedString 2

    CHENYILONG Blog (CoreText框架)NSAttributedString 2 Fullscreen © chenyilong. Powered by Postach.io Blog

  6. CALayer的上动画的暂停和恢复

    CHENYILONG Blog CALayer上动画的暂停和恢复 #pragma mark 暂停CALayer的动画-(void)pauseLayer:(CALayer*)layer{CFTimeIn ...

  7. CodeForces 816C 思维

    On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as fo ...

  8. HDU 2094 产生冠军 dfs加map容器

    解题报告:有一群人在打乒乓球比赛,需要在这一群人里面选出一个冠军,现在规定,若a赢了b,b又赢了c那么如果a与c没有比赛的话,就默认a赢了c,而如果c赢了a的话,则这三个人里面选不出冠军,还有就是如果 ...

  9. sklearn进行拟合

    # codind:utf-8 from sklearn.linear_model import SGDRegressor,LinearRegression,Ridge from sklearn.pre ...

  10. python概念-其实只要简单了解一下,但是却讲了将近两个小时的知识点:元类

    说实话,我真心不太想总结这个东西,算了,炒一下egon的吧 1 引子 1 class Foo: 2 pass 3 4 f1=Foo() #f1是通过Foo类实例化的对象 python中一切皆是对象,类 ...