当前位置: 首页 > 编程日记 > 正文

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

前言

本节的主题是ASP.NET Web API怎样将控制器动作的返回值转换成HTTP的响应消息。

Web API控制器动作能够返回下列的不论什么值:
1。 void
2。 HttpResponseMessage
3, IHttpActionResult
4, Some other type

取决于返回的以上哪一种。Web API使用不同的机制来创建HTTP响应。

Return typeHow Web API creates the response
voidReturn empty 204 (No Content)
HttpResponseMessageConvert directly to an HTTP response message.
IHttpActionResultCall ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other typeWrite the serialized return value into the response body; return 200 (OK).

本节的剩余部分将具体描写叙述每种返回值。

void

假设返回类型是type,Web API就会用状态码204(No Content)返回一个空HTTP响应。

演示样例控制器:

public class ValuesController : ApiController
{public void Post(){}
}

HTTP对应:

HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 02:13:26 GMT

HttpResponseMessage

假设一个动作返回HttpResponseMessage,Web API就通过HttpResponseMessage的属性构造成消息从而直接将返回值转换成HTTP响应。

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(20)};return response;} 
}

对应:

HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMThello

假设传递一个域模型给CreateResponse方法。Web API会使用媒体格式(media formatter)将序列化模型写入到响应体中。

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;
}

IHttpActionResult

IHttpActionResult接口在Web API 2中被引进。本质上,它定义了一个HttpResponseMessage工厂。下面是使用IHttpActionResult接口的优点:
1, 简单你的控制器的单元測试
2。 为创建HTTP对应将公共逻辑移动到单独的类
3。 通过隐藏构建对应的底层细节。使控制器动作更清晰

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 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMThello

更通常的情况是,你会使用System.Web.Http.Results命名空间下定义的IHttpActionResult实现。

在接下来的演示样例中,假设请求没有匹配到不论什么已存在的产品ID。控制器就会调用ApiController.NotFound来创建一个404(Not Found)响应。否则,控制器会调用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
}

Other Return Types

对于其它全部返回类型。Web API使用媒体格式(media formatter)来序列化返回值。

Web API将序列化值写入到响应体中。响应状态码是200(OK)。

public class ProductsController : ApiController
{public IEnumerable<Product> Get(){return GetAllProductsFromDB();}
}

该实现的缺点在于你不能直接返回一个错误码,比方404。

Web API通过在请求中使用Accept头来选择格式。

演示样例请求:

GET http://localhost/api/products HTTP/1.1
User-Agent: Fiddler
Host: localhost:24127
Accept: application/json

演示样例对应:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT
Content-Length: 56[{"Id":1,"Name":"Yo-yo","Category":"Toys","Price":6.95}]

转载于:https://www.cnblogs.com/brucemengbm/p/7250132.html

相关文章:

前端开发常用单词

methods 方法 mounted 创建完成 export 输出 default 默认的 install 安装 components 组件 template 模板 params 参数 route 路线;途径 package 包;盒子;袋 ; toutes 路由器 plugin 插件 local host 本地 require 需要;依赖; storage 储存 prototype 原型 …

原生ajax的post操作

xml.open(方法&#xff0c;路径&#xff0c;是否开启异步)&#xff1b; console.log(e);来找出数据所在位置&#xff1b; 调用 ajax只能传二进制或字符串&#xff0c;需要先把json转一下&#xff0c;JSON.stringify()&#xff1b; 获取到数据时我们要通过JSON.parse()再转成JSO…

jquery后学什么_我在训练营两年后学到了什么

jquery后学什么by Kara Luton卡拉卢顿(Kara Luton) 我在训练营两年后学到了什么 (What I’ve Learned Two Years Post-Bootcamp) It’s been two entire years since I left behind my career of being a music publicist — one I worked towards all of college and miracul…

ExecutorService 的理解与使用

接口 Java.util.concurrent.ExecutorService 表述了异步执行的机制&#xff0c;并且可以让任务在后台执行。壹個 ExecutorService 实例因此特别像壹個线程池。事实上&#xff0c;在 java.util.concurrent 包中的 ExecutorService 的实现就是壹個线程池的实现。 ExecutorService…

前后端交互,网络请求

这边文章主要根据我自己的前端开发工作经验&#xff0c;东拼西凑出来的一点理解&#xff0c;希望能够对大家有点帮助&#xff0c;如果有误导或者错误的地方还请帮助指正&#xff0c;感谢&#xff01;&#xff01;&#xff01; 前后端交互我理解主要分为三个主要的部分&#xf…

HDU 1877 另一个版本 A+B

另一个版本 AB Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 12894 Accepted Submission(s): 4901Problem Description输入两个不超过整型定义的非负10进制整数A和B(<231-1)。输出AB的m (1 < m <10…

gatsby_如何使用Gatsby.js来获取内容

gatsbyby Dimitri Ivashchuk由Dimitri Ivashchuk 如何使用Gatsby.js来获取内容 (How to source content with Gatsby.js) Gatsby.js is a powerful static site generator (with dynamic capabilities) which can be used to build super performant web-sites. It has a very…

使用 AFNetworking 进行 XML 和 JSON 数据请求

&#xff08;1&#xff09;XML 数据请求 使用 AFNetworking 中的 AFHTTPRequestOperation 和 AFXMLParserResponseSerializer&#xff0c;另外结合第三方框架 XMLDictionary 进行数据转换 使用 XMLDictionary 的好处&#xff1a;有效避免自行实现 NSXMLParserDelegate 委托代理…

批处理+定时任务实现定时休息提醒

前言&#xff1a;俗话说的好&#xff0c;懒是第一生产力&#xff0c;懒是提高生产效率的必要条件。而现今windows是大部分人的第一生产工具&#xff0c;批处理定时任务这对黄金搭档就是提升生产效率的第一工具。大家在生产过程中经常会遇到各种周期性的重复的工作&#xff0c;比…

后端返回的数据中换行符 html换行

标签代码 <span v-html"model3_txt"></span> vue js代码 var txt "恭喜你\n获得某某某奖品"; if(txt.indexOf(\n)!-1){var reg new RegExp("/r/n", "g");txttxt.replace(reg, "<br/>");console.log(t…

vim block vim_如何不再害怕Vim

vim block vim精选最流行的命令以及如何使用它们 (A curation of the most popular commands and how to use them) If you’ve ever used Vim, you know how difficult it can get to reach the same speed as in a “normal” GUI editor. But once you do, the payoff is ex…

android EditText 限定中文个数与英文个数的解决方式

EditText 限定中文8个英文16个的解决方法。 在EditText上控件提供的属性中有限定最大最小长度的方法。可是&#xff0c;对于输入时&#xff0c;限定中文8个英文16个时&#xff0c;怎么办&#xff1f;相当于一个中文的长度是两个英文的长度。原理就不说了。自己看一下android的源…

根据二叉树的前序遍历和中序遍历重建二叉树

题目描述 输入某二叉树的前序遍历和中序遍历的结果&#xff0c;请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}&#xff0c;则重建二叉树并返回。1 /**2 * Definition for …

VUE 监听当前路由 侦听器 watch

侦听器&#xff1a; 你可以利用侦听器&#xff0c;响应数据的变化&#xff0c;例如路由&#xff0c;和页面中data的值&#xff0c;可以在他们变化的时候写相应的处理逻辑在侦听器中。 侦听器的使用很简单&#xff1a; watch 对象就是侦听器&#xff0c;只有当侦听的值改变了它…

如何使用Bootstrap4和ES6创建自定义确认框

by Prashant Yadav通过Prashant Yadav 如何使用Bootstrap4和ES6创建自定义确认框 (How to create a custom confirm box with Bootstrap4 and ES6) We put lots of sweat into achieving a good design, but imagine a scenario where we have to use something which is styl…

RequireJS学习笔记(转)

前言进入移动前端是很不错的选择&#xff0c;这块也是我希望的道路&#xff0c;但是不熟悉啊。。。现在项目用的是requirebackbone&#xff0c;整个框架被封装了一次&#xff0c;今天看了代码搞不清楚&#xff0c;觉得应该先从源头抓起&#xff0c;所以再看看require了。上午是…

火狐中的table

在火狐浏览器中&#xff0c;table的th、td会存在小数转载于:https://www.cnblogs.com/likwin/p/7270817.html

React路由 react-router-dom

React的路由&#xff1a; 首先我们创建一个React应用 npm install -g create-react-app create-react-app demo-app cd demo-app安装路由 npm install react-router-dom npm add babel/runtime 接下来&#xff0c;将以下任一示例复制/粘贴到中src/App.js。 第一个示例&…

编程基础 垃圾回收_为什么我回收编程问题

编程基础 垃圾回收by Amy M Haddad通过艾米M哈达德(Amy M Haddad) 为什么我回收编程问题 (Why I Recycle Programming Problems) Many programmers are given the same advice: solve as many problems as possible. It’s true that solving new problems can help you gain …

SQL Server孤立账户解决办法

选择你想要的数据库。 执行 exec sp_change_users_login UPDATE_ONE,用户名,登录名 假如你的登录名是&#xff1a;sd exec sp_change_users_login UPDATE_ONE,sd,sd 转载于:https://www.cnblogs.com/runliuv/p/7273675.html

vue更新data无效,页面data没刷新 vue.set

Vue中组件的data是有很多坑的&#xff0c;先普及一下常识&#xff1a; 1.想使用data&#xff0c;必须先在data中创建。&#xff08;如果不创建就会报错&#xff09;示例&#xff1a; <div class"">{{user.Age}}</div>new Vue({el: #app,data: {user:{A…

重温Thinking in java

1、高精度 BigInteger、BigDecimal 支持任意大小的数字 不能使用运算符 运算速度相对于int、float稍慢 2、对象作用域 {String s new String("aaa"); } 在}外 此时栈中的引用s已经超出了自己的作用域 便不存在了 但是new String("aaa")这个堆中的对象仍然…

2018 react 大会_React Conf 2018的经验教训

2018 react 大会by Yangshun Tay阳顺泰 React Conf 2018的经验教训 (Lessons Learned at React Conf 2018) I was fortunate to have attended React Conf 2018 thanks to my managers — it was an awesome event. I have been watching past React Conf videos online and i…

删除url中某个参数

这里的url 是指一个网站链接 例如&#xff1a; https://baidu.com?a1&b2 下面看一下封装的代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><script src"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js&q…

【转载】MSXML应用总结 开发篇(下)

原文&#xff1a;http://blog.sina.com.cn/s/blog_48f93b530100eq4b.html 三、查询XML文档节点 这部分属于“读”XML文档并做节点遍历&#xff0c;由于担心加上实例会占用过多的篇幅影响阅读&#xff0c;先在这篇做方法总结&#xff0c;以后有时间再写一篇“实战篇”专门写个实…

d010:盈数、亏数和完全数

题目: 对一个正整数N而言&#xff0c;将它除了本身以外所有的因子加起来的总和为S&#xff0c;如果S>N&#xff0c;则N为盈数&#xff0c;如果S<N&#xff0c;则N为亏数&#xff0c;而如果SN&#xff0c;则N为完全数&#xff08;Perfect Number&#xff09;。例如10的因子…

软件开发 理想_我如何在12个月内找到理想的软件工作

软件开发 理想In this talk, Matt Woods shares the 3 cornerstone habits that helped him land his dream software job in just 12 months. These habits paved the way for him to consistently grow as a software developer, balloon his professional network, and easi…

Angular4.0从入门到实战打造在线竞拍网站学习笔记之四--数据绑定管道

Angular4.0基础知识之组件Angular4.0基础知识之路由Angular4.0依赖注入Angular4.0数据绑定&管道 数据绑定 数据绑定允许你将组件控制器的属性和方法与组件的模板连接起来&#xff0c;大大降低了开发时的编码量。 常见的表现形式有&#xff1a; 插值表达式&#xff1a;<h…

给GridView增加求和行

1、在WebForm窗体中&#xff0c;设置GridView的ShowFooter"True" 2、在后台代码中 private int jhrs0,ybrs0;//定义变量 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > 0) { jhrs Convert.ToInt16(e.Ro…

phpMyAdmin 数据库添加int类型的值时默认设为唯一主键的问题解决

数据库的表中插入了一条数据&#xff0c;再插入数据就插入不进去。 这是我今天在开发数据库的时候&#xff0c;遇到一个问题&#xff0c;经过排查&#xff0c;是数据库的结构有问题&#xff0c;有字段是唯一数据&#xff0c;但是目前还不想设置它的值。 场景环境描述&#xff…