how ASP.NET Web API converts the return value from a controller action into an HTTP response message.

ASP.NET Web API如何将返回值从控制器操作转换为HTTP响应消息。

Web API控制器操作可以返回以下任何内容:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. 其他一些类型

根据返回的内容,Web API使用不同的机制来创建HTTP响应。

返回类型                               Web API如何创建响应
void 返回空204(无内容)
HttpResponseMessage 直接转换为HTTP响应消息。
IHttpActionResult 调用ExecuteAsync以创建HttpResponseMessage,然后转换为HTTP响应消息。
其他类型 将序列化的返回值写入响应主体; 返回200(OK)。

HttpResponseMessage

如果操作返回HttpResponseMessage,则Web API将返回值直接转换为HTTP响应消息,使用HttpResponseMessage对象的属性来填充响应。

此选项使您可以对响应消息进行大量控制。例如,以下控制器操作设置Cache-Control标头。

public class ValuesController : ApiController
{
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes()
};
return response;
}
}

响应:

HTTP/1.1  OK
Cache-Control: max-age=
Content-Length:
Content-Type: text/plain; charset=utf-
Server: Microsoft-IIS/8.0
Date: Mon, Jan :: GMT hello

如果将域模型传递给CreateResponse方法,则Web API使用媒体格式化程序将序列化模型写入响应正文。

public HttpResponseMessage Get()
{
// Get a list of products from a database.
IEnumerable<Product> products = GetProductsFromDB(); // Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}

Web API使用请求中的Accept标头来选择格式化程序。

IHttpActionResult

IHttpActionResult包含一个方法ExecuteAsync,它异步创建一个HttpResponseMessage实例。

public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
如果控制器操作返回IHttpActionResult,则Web API调用ExecuteAsync方法以创建HttpResponseMessage。然后它将HttpResponseMessage转换为HTTP响应消息。
这是IHttpActionResult的简单实现,它创建了一个纯文本响应:
public class TextResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request; public TextResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}

控制器动作示例:

public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new TextResult("hello", Request);
}
}

响应:

HTTP/1.1  OK
Content-Length:
Content-Type: text/plain; charset=utf-
Server: Microsoft-IIS/8.0
Date: Mon, Jan :: GMT hello

通常,您将使用System.Web.Http.Results命名空间中定义的IHttpActionResult实现。该ApiController类定义辅助方法返回这些内置的动作效果。

在以下示例中,如果请求与现有产品ID不匹配,则控制器调用ApiController.NotFound以创建404(未找到)响应。否则,控制器调用ApiController.OK,它会创建包含产品的200(OK)响应。

public IHttpActionResult Get (int id)
{
Product product = _repository.Get (id);
if (product == null)
{
return NotFound(); // Returns a NotFoundResult
}
return Ok(product); // Returns an OkNegotiatedContentResult
}

Web API 2中的操作结果的更多相关文章

  1. Web API 2 入门——Web API 2中的操作结果(谷歌翻译)

    在这篇文章中 空虚 HttpResponseMessage IHttpActionResult 其他返回类型 作者:Mike Wasson 本主题描述ASP.NET Web API如何将控制器操作的返 ...

  2. 不借助工具在浏览器中通过Web API执行Dynamics 365操作(Action)实例

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

  3. [译] 在Web API 2 中实现带JSON的Patch请求

    原文链接:The Patch Verb in Web API 2 with JSON 我想在.NET4.6 Web API 2 项目中使用Patch更新一个大对象中的某个字断,这才意识到我以前都没有用 ...

  4. 利用Fiddler修改请求信息通过Web API执行Dynamics 365操作(Action)实例

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

  5. 从ASP.Net Core Web Api模板中移除MVC Razor依赖项

    前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC   VS WebApi (1)在ASP. ...

  6. Web API项目中使用Area对业务进行分类管理

    在之前开发的很多Web API项目中,为了方便以及快速开发,往往把整个Web API的控制器放在基目录的Controllers目录中,但随着业务越来越复杂,这样Controllers目录中的文件就增加 ...

  7. ASP.NET Web API 2 中的属性路由使用(转载)

    转载地址:ASP.NET Web API 2 中的属性路由使用

  8. Web API 2中的属性路由

    Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...

  9. 【Web API系列教程】1.2 — Web API 2中的Action Results

    前言 本节的主题是ASP.NET Web API怎样将控制器动作的返回值转换成HTTP的响应消息. Web API控制器动作能够返回下列的不论什么值: 1. void 2. HttpResponseM ...

随机推荐

  1. 50行代码实现缓存,JAVA内存模型原理

    遇见这样的高人怎么办??下面是一个简单缓存的实现,相当牛叉!自己看吧,只有50行代码. 摘自:http://www.oschina.net/code/snippet_55577_3887 import ...

  2. [Python爬虫] 之二十三:Selenium +phantomjs 利用 pyquery抓取智能电视网数据

    一.介绍 本例子用Selenium +phantomjs爬取智能电视网(http://news.znds.com/article/news/)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字 ...

  3. ubuntu各版本代号(更新至15.04)及各版本下载地址等

    版本号 代号 发布时间 15.04 Vivid Vervet 2015/04/22 14.10 Utopic Unicorn 2014/10/23 14.04 LTS Trusty Tahr 2014 ...

  4. 通过浏览器查看nginx服务器状态配置方法

    通过浏览器查看nginx服务器状态配置方法 投稿:junjie 字体:[增加 减小] 类型:转载 这篇文章主要介绍了通过浏览器查看nginx服务器状态配置方法,本文讲解开启nginx-status的配 ...

  5. WP8简单的计算器

    <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinition ...

  6. 记一次SmtpClient发送邮件引发的系列问题

    前提:公司同事离职,我接手同事负责的项目. 事件:某天公司的分析人员,说软件中的邮件发送功能不能使用,总是提示"邮件发送失败". 本地能够正常发送,发布WCF到服务器IIS上,再调 ...

  7. 自己实现strcpy函数

    #include //printf #include //ssert #include //malloc #include //strlen char * sstrcpy(char * strdst, ...

  8. position与float属性的使用

    1.使用float时,可以说是用于布局,取值主要有left.right.none.就是将该块的元素浮动起来,在浏览器默认的情况下,该元素的位置是为空的, 即脱离了文档流而存在,如果有其他元素,那么这些 ...

  9. Android 第三方应用广告拦截实现

    前段时间,公司制造的机器里应用装有不良广告,严重影响了儿童客户使用者的思想健康.导致被人投诉. 于是乎.就有了想研发一款相似于360广告屏蔽的应用的念头.嗯.事情就是这样.如今切入主题. 眼下市场上有 ...

  10. 手动grub引导redhat

    grub是redhat默认的引导程序,在安装redhat时会提示是否安装bootloader,但自己手贱选择不安装,待系统重启时就是grub命令行界面,不能直接进系统.瞬时感觉麻烦大了,只能手动输入咯 ...