设为首页 加入收藏

TOP

IHttpActionResult 返回值类型(一)
2017-10-13 10:43:22 】 浏览:9053
Tags:IHttpActionResult 返回 类型

Asp.Net WebAPI服务函数的返回值主要可以分为void、普通对象、HttpResponseMessag、IHttpActionResult e四种,本文这里简单的介绍一下它们的区别。

一、返回void

返回void一般常用于Put和Delete函数。

    public void Delete(int id)
    {
    }

当服务函数执行完成后,服务器端并不是啥都不干直接把客户端给断掉,而是发送一个标准的204 (No Content)的Http应答给客户端。

    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?Zjpc5paH5qGjXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xXZWJBcHBsaWNhdGlvbjFcV2ViQXBwbGljYXRpb24xXGFwaVx2YWx1ZXNcMQ==?=
    X-Powered-By: ASP.NET
    Date: Fri, 02 May 2014 13:32:07 GMT

 

二、返回普通对象

返回普通对象时,服务器将返回的对象序列化后(默认是json),通过Http应答返回给客户端。例如,

    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "hello";
        }
    }

此时的返回结果是:

    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?Zjpc5paH5qGjXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xXZWJBcHBsaWNhdGlvbjFcV2ViQXBwbGljYXRpb24xXGFwaVx2YWx1ZXM=?=
    X-Powered-By: ASP.NET
    Date: Fri, 02 May 2014 12:54:18 GMT
    Content-Length: 7

    "hello"

异步返回普通对象:

WebAPI也是支持异步返回对象的:

    public async Task<string> Get()
    {
        await Task.Delay(100);
        return "hello";
    }

异步返回的时候,服务器异步等待函数执行完成后再将返回值返回给对象。由于这个过程对于客户端来说是透明的,这里就不列举报文了。

 

三、返回HttpResponseMessage

HttpResponseMessage是标准Http应答了,此时服务器并不做任何处理,直接将HttpResponseMessage发送给客户端。

    public HttpResponseMessage Get()
    {
        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent("hello", Encoding.UTF8);
            
        return response;
    }

此时的返回结果如下:

    HTTP/1.1 200 OK
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Length:

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C# 序列化 下一篇多线程(6)线程同步

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目