https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

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

A Web API controller action can return any of the following:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Some other type

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response.

Return type How Web API creates the response
void Return empty 204 (No Content)
HttpResponseMessage Convert directly to an HTTP response message.
IHttpActionResult Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other type Write the serialized return value into the response body; return 200 (OK).

The rest of this topic describes each option in more detail.

void

If the return type is void, Web API simply returns an empty HTTP response with status code 204 (No Content).

Example controller:

  public class ValuesController : ApiController
{
[HttpGet]
public void Post()
{
}
}

request

GET http://localhost/Chuck_WebApi/api/values/post HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 10:04:57 GMT

HttpResponseMessage

If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response.

This option gives you a lot of control over the response message. For example, the following controller action sets the Cache-Control header.

需要把路由从默认的routeTemplate: "api/{controller}/{id}"调整为routeTemplate: "api/{controller}/{action}/{id}"

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

request

GET http://localhost/Chuck_WebApi/api/values/get HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 10:25:14 GMT

hello

If you pass a domain model to the CreateResponse method, Web API uses a media formatter to write the serialized model into the response body.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

https://autofaccn.readthedocs.io/en/latest/integration/webapi.html

此处代码的前提是,在项目启动的时候,使用了Autofac.WebApi2初始化GlobalConfiguration.Configuration.DependencyResolver

 public HttpResponseMessage Get2()
{
var dependencyResolver = GlobalConfiguration.Configuration.DependencyResolver;
var controller = dependencyResolver.GetService(typeof(ProductsController));
ProductsController productsController = controller as ProductsController;
//productsController.ControllerContext //might need set value here // Get a list of products from a database.
IEnumerable<Product> products = productsController.GetAllProducts(); // Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}

Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.

request

GET http://localhost/Chuck_WebApi/api/values/get2 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 11:13:15 GMT
Content-Length: 182

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

IHttpActionResult

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.

public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}

If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

Here is a simple implementaton of IHttpActionResult that creates a plain text response:

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

Example controller action:

 public IHttpActionResult Get3()
{
return new TextResult("hello", Request);
}

request

GET http://localhost/Chuck_WebApi/api/values/get3 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:19:02 GMT

hello

More often, you will use the IHttpActionResult implementations defined in the System.Web.Http.Results namespace. The ApiController class defines helper methods that return these built-in action results.

https://docs.microsoft.com/en-us/previous-versions/aspnet/dn314678(v=vs.118)    系统内定的一些IHttpActionResult 的实现

ApiController 本身也内置了一部分的方法,来返回对应的实现

BadRequestErrorMessageResult

UnauthorizedResult

In the following example, if the request does not match an existing product ID, the controller calls ApiController.NotFound to create a 404 (Not Found) response.

Otherwise, the controller calls ApiController.OK, which creates a 200 (OK) response that contains the product.

public IHttpActionResult Get4(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound(); // Returns a NotFoundResult
}
return Ok(product); // Returns an OkNegotiatedContentResult
}

request1

GET http://localhost/Chuck_WebApi/api/values/get4/3 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response1

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:36:31 GMT
Content-Length: 60

{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}

request2

GET http://localhost/Chuck_WebApi/api/values/get4/4 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response2

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:50:06 GMT
Content-Length: 0

Other Return Types

For all other return types, Web API uses a media formatter to serialize the return value.

Web API writes the serialized value into the response body.

The response status code is 200 (OK).

public IEnumerable<Product> GetAllProducts()
{
return products;
}

A disadvantage of this approach is that you cannot directly return an error code, such as 404.

However, you can throw an HttpResponseException for error codes.

For more information, see Exception Handling in ASP.NET Web API.

Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.

request

GET http://localhost/Chuck_WebApi/api/products/getallproducts HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 03:10:56 GMT
Content-Length: 182

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

Action Results in Web API 2的更多相关文章

  1. web api :Action Results in Web API 2

    原文:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results Web api 返回 ...

  2. Web API 2中的Action Results

    [译]Action Results in Web API 2 单击此处查看原文 本文阐述了ASP.NET Web API是如何将controller action的返回值转换为HTTP respons ...

  3. ASP.NET Web API 2中的错误处理

    前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...

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

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

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

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

  6. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  7. Web APi入门之Self-Host寄宿及路由原理(二)

    前言 刚开始表面上感觉Web API内容似乎没什么,也就是返回JSON数据,事实上远非我所想,不去研究不知道,其中的水还是比较深,那又如何,一步一个脚印来学习都将迎刃而解. Self-Host 我们知 ...

  8. 实战 ASP.NET Web API

    Web API 框架是一个面向 Http 协议的通信框架.相对于 WCF 而言,Web API 只面向于 Http 协议设计,而且没有 WCF 那么繁琐的配置.Web API 的开发类似于 ASP.N ...

  9. 【转载】ASP.NET MVC Web API 的路由选择

    此文章描述了ASP.NET Web API如何将Http请求路由到controller. 路由表 在ASP.NET Web API中,controller是用来处理HTTP请求的一个类.这个类中用于处 ...

随机推荐

  1. 【BZOJ4567】[Scoi2016]背单词 Trie树+贪心

    [BZOJ4567][Scoi2016]背单词 Description Lweb 面对如山的英语单词,陷入了深深的沉思,“我怎么样才能快点学完,然后去玩三国杀呢?”.这时候睿智 的凤老师从远处飘来,他 ...

  2. 170111、MapperScannerConfigurer处理过程源码分析

    前言 本文将分析mybatis与spring整合的MapperScannerConfigurer的底层原理,之前已经分析过java中实现动态,可以使用jdk自带api和cglib第三方库生成动态代理. ...

  3. IDEA 设置代码模板

    一.代码模板 参考: IntelliJ IDEA 使用(一)基本设置与类.方法模板设置 - 云 + 社区 - 腾讯云 文件代码模板的使用 - IntelliJ IDEA 使用教程 - 极客学院 Wik ...

  4. node.js开发学习一HelloWorld

    前言:由于公司业务需求,最近启动了node.js的开发任务,想把自己的开发学习历程记录记录下来,可以增加记忆,也方便查找.虽然对javascript有一定的了解,但是刚接触node.js的时候,发现还 ...

  5. 个案排秩 Rank (linear algebra) 秩 (线性代数)

    非叫“秩”不可,有秩才有解_王治祥_新浪博客http://blog.sina.com.cn/s/blog_8e7bc4f801012c23.html 我在一个大学当督导的时候,一次我听一位老师给学生讲 ...

  6. 转!!SQL左右连接中的on and和on where的区别

    原博文地址:http://blog.csdn.net/xingzhemoluo/article/details/39677891 原先一直对SQL左右连接中的on and和on where的区别不是太 ...

  7. CNI Proposal 摘要

    原文连接:https://github.com/containernetworking/cni/blob/master/SPEC.md General consideration CNI的想法是先让容 ...

  8. 我的Android进阶之旅------>解决:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

    错误描述 今天在Android Studio项目中加入了jackson的开发包,编译运行时候,引发了如下的错误: Error:Execution failed for task ':app:trans ...

  9. Django - 权限(1)

    一.权限表结构设计 1.认识权限 生活中处处有权限,比如,腾讯视频开会员才有观看某个最新电影的权限,你有房间钥匙就有了进入这个房间的权限,等等.同样,程序开发过程中也有权限,我们今天说的权限指的是we ...

  10. *.hbm.xml映射文件的元素及属性

    1. 每个持久化对象都需要提供一个以类名命名的映射文件,映射文件需要放在和po类同一目录下. 2. 如下是wefepo的映射文件: <hibernate-mapping> <clas ...