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. Hive中日期函数总结

    --Hive中日期函数总结: --1.时间戳函数 --日期转时间戳:从1970-01-01 00:00:00 UTC到指定时间的秒数 select unix_timestamp(); --获得当前时区 ...

  2. 小程序app is not defined

    错误记录: 小程序丨 报错:app is not defined; 解决方案: Js头部添加:var app = getApp();     返回按钮: wx.navigateBack();   转发 ...

  3. JAVA IO操作:数据操作流:DataOutputStream和DataInputStream

    掌握DataOutputStream和DataInputStream的作用. 可以使用DataOutputStream和DataInputStream写入和读取数据. 在IO包中提供了两个与平台无关的 ...

  4. webpack打包vue2.0项目时必现问题(转载)

    原文地址:http://www.imooc.com/article/17868 [Vue warn]: You are using the runtime-only build of Vue wher ...

  5. 20181011_matplotlib

    import numpy as np import pandas as pd import matplotlib.pyplot as plt df=pd.DataFrame(np.random.ran ...

  6. 收藏 Silverlight中子窗体关闭刷新父窗体(转载)

        public partial class MainPage : UserControl    {        public MainPage()        {            In ...

  7. javascript跨浏览器事件对象类库

    一.前言 学习了javascript事件后,个人总结归纳了跨浏览器事件对象类库,方便以后使用,现分享给大家. 二.事件对象封装 将对浏览器事件对象的操作封装成eventObject.js方便调用 // ...

  8. C6455 CSL_EMIF详解

    C6455 CSL_EMIF详解 原网址http://www.61ic.com/Article/C6000/C64X/201303/47507.html C6455CSL详解 和DSP6455的EMI ...

  9. Mac系统下配置JDK及MAVEN环境变量配置

    1. 启动终端Terminal 2.进入当前用户的home目录 输入cd ~ 3.临时授权,sudo su: 输入密码(密码不显示): 4.创建.bash_profile 输入touch .bash_ ...

  10. Python学习之格式符

    %s    字符串 (采用str()的显示) %r    字符串 (采用repr()的显示) %c    单个字符 %b    二进制整数 %d    十进制整数 %i    十进制整数 %o    ...