Web API 2:Action的返回类型
Web API 2:Action的返回类型
Web API控制器中的Action方法有如下几种返回类型:
- void
- HttpResponseMessage
- IHttpActionResult
- 其它类型
基于上面几种不同的返回类型,Web API创建HTTP响应消息的机制也不同。
| 返回类型 | Web API创建HTTP响应消息的机制 |
|---|---|
| void | 返回HTTP状态码204(无内容) |
| HttpResponseMessage | 直接转换成HTTP响应消息 |
| IHttpActionResult | 调用接口的ExecuteAsync方法创建一个HttpResponseMessage对象,然后转换成HTTP响应消息 |
| 其它类型 | 把序列化后的返回值写入响应正文,并且返回HTTP状态码200(OK) |
void

public class ReturnValueDemoController : ApiController
{
//返回类型为void
public void Get()
{
}
}


HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 14:34:09 GMT

HttpResponseMessage

public class ReturnValueDemoController : ApiController
{
//返回类型为HttpResponseMessage
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode .OK, "hello");
response.Content = new StringContent ( "hello wep api", Encoding .Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan .FromSeconds(600)
};
return response;
}
}


HTTP/1.1 200 OK
Cache-Control: max-age=600
Content-Type: text/plain; charset=utf-16
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 15:14:05 GMT
Content-Length: 26 hello wep api

public HttpResponseMessage Get()
{
IQueryable <Product > products = repository.GetProducts();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode .OK, products);
return 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/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 15:37:51 GMT
Content-Length: 264 [{"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":2,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":3,"Name":"洗发水","Description":null,"Price":20.0,"Category":"日用品"}]

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

public class PlainTextResult : IHttpActionResult
{
private string text;
private HttpRequestMessage request; public PlainTextResult(string text, HttpRequestMessage request)
{
this .text = text;
this .request = request;
}
public Task < HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response=new HttpResponseMessage
{
Content = new StringContent (text, Encoding.Unicode),
RequestMessage = request
};
return Task .FromResult(response);
}
}

//返回类型是IHttpActionResult
public IHttpActionResult Get()
{
return new PlainTextResult( "plain text result" ,Request);
}

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-16
Expires: -1
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtbw==?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:17:30 GMT
Content-Length: 34 plain text result


HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w1?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:54:21 GMT
Content-Length: 0


HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1wx?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 16:53:16 GMT
Content-Length: 82 {"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"}

其它返回类型
public IQueryable < Product> GetpProducts()
{
return repository.GetProducts();
}

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcV29ya1NwYWNlXERvdE5ldFxNdmNEZW1vXE12Y0RlbW8uV2ViVUlcYXBpXFJldHVyblZhbHVlRGVtb1w=?=
X-Powered-By: ASP.NET
Date: Wed, 04 Mar 2015 17:03:13 GMT
Content-Length: 264 [{"ProductId":1,"Name":" 苹果","Description":null,"Price":1.0,"Category":"水果"},{"ProductId":2,"Name":"鼠标","Description":null,"Price":50.0,"Category":"电脑配件"},{"ProductId":3,"Name":"洗发水","Description":null,"Price":20.0,"Category":"日用品"}]


public Product GetProductById( int id)
{
Product product = repository.GetProductById(id);
if (product==null )
throw new HttpResponseException ( HttpStatusCode.NotFound); return product;
}

Web API 2:Action的返回类型的更多相关文章
- ASP.NET Web API 通过参数控制返回类型(JSON|XML)
一个很实用的技巧,可以在访问web api服务的时候指定返回数据的格式类型,比如 json 或者 xml. 因为 web api 默认返回的是XML格式,但是现在json 比较流行,同时网上也有其他的 ...
- 通过Web API调用Action时各种类型输入参数传递值的方法
本人微信公众号:微软动态CRM专家罗勇 ,回复280或者20180906可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . Dy ...
- 如何让ASP.NET Web API的Action方法在希望的Culture下执行
在今天编辑推荐的<Hello Web API系列教程--Web API与国际化>一文中,作者通过自定义的HttpMessageHandler的方式根据请求的Accep-Language报头 ...
- Only one complex type allowed as argument to a web api controller action.
错误内容: message":"An error has occurred.","exceptionMessage":"Only one c ...
- ASP.NET Web API 2:Action的返回类型
Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 基于上面几种不同的返回类型,Web API ...
- Web API对application/json内容类型的CORS支持
假设有一简单架构分为前后两部分,其一是Angular构成的前端页面站点,另一个则是通过ASP.NET Web API搭建的后端服务站点.两个站点因为分别布署,所有会有CORS(Cross-Origin ...
- ASP.NET Core Web API 控制器与方法返回输出
DATA ACCESS LAYER 在一些不同的示例教程中,我们可能看到 DAL 的实现在主项目中,并且每个控制器中都有实例.我们不建议这么做. 当我们编写 DAL 时,我们应该将其作为一个独立的服务 ...
- ASP.NET Web API 如何通过程序控制返回xml还是json
雖然 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式,並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式,不過有時候我們的確也需要讓程式來控制要回應哪種格式, ...
- Web api Json 接受的参数类型为父类,自动序列化为子类的过程
场景: public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// t ...
随机推荐
- 接近带给你AngularJS - 经验说明示例
接近带给你AngularJS列: 带你走近AngularJS - 基本功能介绍 带你走近AngularJS - 体验指令实例 带你走近AngularJS - 创建自己定义指令 ------------ ...
- 探索Windows Azure 监控和自动伸缩系列3 - 启用Azure监控扩展收集自定义监控数据
上一篇我们介绍了获取Azure的监控指标和监控数据: http://www.cnblogs.com/teld/p/5113376.html 本篇我们继续:监控虚拟机的自定义性能计数器. 随着我们应用规 ...
- 使用JMX实现的内存监控(转)
public final class MemoryWarningSystem { private static MemoryWarningSystem m_instance = null; /** * ...
- NUnit3 Test Adapter vs2015
NUnit的安装 前言:NUnit是什么? NUnit 是一个单元测试框架,专门针对于.NET来写的.NUnit是xUnit家族种的第4个主打产品,完全由C#语言来编写,并且编写时充分利用了许多.NE ...
- HDU 4300 Clairewd’s message(扩展KMP)
思路:extend[i]表示原串以第i開始与模式串的前缀的最长匹配.经过O(n)的枚举,我们能够得到,若extend[i]+i=len且i>=extend[i]时,表示t即为该点之前的串,c即为 ...
- 一张漫画说尽IT开发过程
- jQuery、Ajax分页
1.效果预览 2.HTML代码 <div class="row"> <div class="col-lg-12 col-sm-12 col-xs-12 ...
- 每天一点点java---继承exception类来实现自己的异常类
package prac_1; /** * <p>Title: 捕获异常和实现自己的异常类</p> * <p>Description: 通过继承Exception类 ...
- 于XAML导入命名空间的代码
例如,下面的代码到指定的命名空间.不仅导入的命名空间,并且还为指定的命名空间前缀local.当然,你也可以指定一个前缀为另一个名称,这可以定义.导入后,市民可以在命名当前空间XAML使用代码.例如,在 ...
- 阿里云ECSserver部署django
highlight=uwsgi%20django">參考 server安装的是Centos 系统. uwsgi是使用pip安装的. nginx是使用yum install nginx安 ...