Web API 2中的操作结果
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控制器操作可以返回以下任何内容:
- void
- HttpResponseMessage
- IHttpActionResult
- 其他一些类型
根据返回的内容,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中的操作结果的更多相关文章
- Web API 2 入门——Web API 2中的操作结果(谷歌翻译)
在这篇文章中 空虚 HttpResponseMessage IHttpActionResult 其他返回类型 作者:Mike Wasson 本主题描述ASP.NET Web API如何将控制器操作的返 ...
- 不借助工具在浏览器中通过Web API执行Dynamics 365操作(Action)实例
摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复262或者20170727可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyon ...
- [译] 在Web API 2 中实现带JSON的Patch请求
原文链接:The Patch Verb in Web API 2 with JSON 我想在.NET4.6 Web API 2 项目中使用Patch更新一个大对象中的某个字断,这才意识到我以前都没有用 ...
- 利用Fiddler修改请求信息通过Web API执行Dynamics 365操作(Action)实例
本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复261或者20170724可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...
- 从ASP.Net Core Web Api模板中移除MVC Razor依赖项
前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC VS WebApi (1)在ASP. ...
- Web API项目中使用Area对业务进行分类管理
在之前开发的很多Web API项目中,为了方便以及快速开发,往往把整个Web API的控制器放在基目录的Controllers目录中,但随着业务越来越复杂,这样Controllers目录中的文件就增加 ...
- ASP.NET Web API 2 中的属性路由使用(转载)
转载地址:ASP.NET Web API 2 中的属性路由使用
- Web API 2中的属性路由
Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...
- 【Web API系列教程】1.2 — Web API 2中的Action Results
前言 本节的主题是ASP.NET Web API怎样将控制器动作的返回值转换成HTTP的响应消息. Web API控制器动作能够返回下列的不论什么值: 1. void 2. HttpResponseM ...
随机推荐
- 深度增强学习--Actor Critic
Actor Critic value-based和policy-based的结合 实例代码 import sys import gym import pylab import numpy as np ...
- char p[]与char *p的区别
#include <iostream> using namespace std; int main(void) { char *pp = "abc";//*pp指向的是 ...
- [转载] 在Linux中,开机自动运行普通用户的脚本程序
FROM:http://blog.csdn.net/sinboy/article/details/2466225 FROM:http://www.2cto.com/os/201006/50680.ht ...
- HDU 4287-Intelligent IME(哈希)
Intelligent IME Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- JS里取前天,昨天和今天
var today=new Date(); var yesterday=new Date(today.getTime()-1000*60*60*24); var thedaybeforeyesterd ...
- 注册表 API 以及开机自启动
注册表是window系统中非常重要的一部分,今天在网上查了一些文章学习了下,觉得其中有一句话总结的很经典:注册表是用来存储信息的. 这句话虽然有点废,但是说的没错.当然,注册表中包含的内容非常多,远没 ...
- PHP函数之HTMLSPECIALCHARS_DECODE
PHP函数之htmlspecialchars_decode htmlspecialchars_decode :将特殊的 HTML 实体转换回普通字符 htmlspecialchars: 将普通 ...
- iOS 转盘动画效果实现
代码地址如下:http://www.demodashi.com/demo/11598.html 近期公司项目告一段落,闲来无事,看到山东中国移动客户端有个转盘动画挺酷的.于是试着实现一下,看似简单,可 ...
- python中的多进程处理
转载于:http://blog.csdn.net/jj_liuxin/article/details/3564365 帮助文档见https://docs.python.org/2.7/library/ ...
- 【MyBatis学习15】MyBatis的逆向工程生成代码
1. 什么是逆向工程 mybatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需 ...