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. npm添加淘宝镜像

    原文:http://cnodejs.org/topic/4f9904f9407edba21468f31e npm是一个很好用的工具,全场是Node Packet Manager,是一个nodejs的包 ...

  2. 查看某一个开发者代码修改量的脚本(ios平台可用)

    #!/bin/sh # This is a script that help you get your team member's productivity # by analyzing his/he ...

  3. Mac电脑下配置maven环境变量

    Mac电脑下配置maven环境变量 打开终端,使用 touch 命令创建 .bash_profile 文件 touch .bash_profile 编辑刚刚创建的文件 .bash_profile vi ...

  4. 一起talk C栗子吧(第二十二回:C语言实例--队列一)

    各位看官们,大家好,上一回中咱们说的是表达式求值的样例,该样例使用了栈,这一回咱们说的是栈的 兄弟:队列. 闲话休提,言归正转.让我们一起talk C栗子吧. 我们在这里说的队列是一种抽象的数据结构, ...

  5. zbar 解析 图片 二维码 条形码

    #!/usr/bin/env python # coding: u8 import os import zbar import Image import urllib import uuid def ...

  6. 移动端H5页面 input 获取焦点时,虚拟键盘挡住input输入框解决方法

    在移动端h5开发的时候,发现如果input在页面底部,当触发input焦点的时候会弹出系统虚拟键盘,虚拟键盘会遮挡input输入框.这会很影响用户体验,于是在网上找到了如下的解决办法: 方法一:使用w ...

  7. 流水线策略 相关算法 Tomasulo算法与记分牌调度算法

    设计流水线策略时,可参考 Tomasulo算法与记分牌调度算法  (这两个是霍老师推荐的算法,自己未了解过)

  8. linux socket读数据错误解释

    EINTR 表示某种阻塞的操作,被接收到的信号中断,造成的一种错误返回值. EAGAIN   从字面上来看,是提示再试一次.这个错误经常出现在当应用程序进行一些非阻塞(non-blocking)操作( ...

  9. 数组传到后台 string[] 获取

    调试的 时候js  断点到后台 js上面也可以查看 传到后台的数据 方便查看~~

  10. #1214 - The used table type doesn't support FULLTEXT indexes解决办法

    #1214 - The used table type doesn't support FULLTEXT indexes报此错误的原因是:InnoDB不支持FULLTEXT类型的索引. 网上的解决办法 ...