zoukankan      html  css  js  c++  java
  • c# WebApi之接口返回类型详解

    Webapi的接口返回值主要有四种类型

    1. void无返回值
    2. IHttpActionResult
    3. HttpResponseMessage
    4. 自定义类型

      void无返回值

      大家都知道void声明的是一个无返回值的方法,声明一个api控制器方法,例如:

    public class ValuesController : ApiController
    {
        [HttpGet]
        public void Get()
        {
            int a = 1;
            int b = 2;
            int c = a + b;
            //.....................
        }
    
        }

    使用postman,测试接口:

    这里写图片描述
    可以看到,void声明的接口,在请求成功的时候得不到返回值,而且会返回http的状态码为204,表示没有返回值。

    IHttpActionResult

    IHttpActionResult是WebApi最常用的一种返回值类型,常用的方式有:Json(T content)、Ok()、 Ok(T content)、NotFound()、Content(HttpStatusCode statusCode, T value)、BadRequest()、Redirect(string location)等

    Json(T content)

    在WebApi的ApiController这个抽象类里面,为我们封装了Json(T content)这个方法,它的用法和MVC里面的JsonResult基本类似。

    [HttpGet]
    public IHttpActionResult getJson()
    {
        var list = new List<userinfo>();
        list.Add(new userinfo { Name="jeck",age=22 });
        list.Add(new userinfo { Name = "poor", age = 23 });
        return Json<List<userinfo>>(list);
    }
    
    private class userinfo{
        public string Name { get; set; }
        public int age { get; set; }
    }

    测试结果: 
    这里写图片描述

    为什么可以返回 Json(T content)呢,转到Json(T content)的定义,发现它返回的是JsonResult对象 
    这里写图片描述

    再转到JsonResult的定义,发现它实现了IHttpActionResult接口 
    这里写图片描述

    当然也可以使用dynamic来返回一个对象

    [HttpGet]
    public IHttpActionResult getJson()
    {
        return Json<dynamic>(new { AA = "a", BB = "b" });
    }

    这里写图片描述

    Ok()、 Ok(T content)

    如果返回Ok(),就表示不向客户端返回任何信息,只告诉客户端请求成功。

    [HttpGet]
    public IHttpActionResult getJson()
    {
        return Ok();
    }

    这里写图片描述

    Ok(T content)向客户端返回一个成功的对象

    [HttpGet]
    public IHttpActionResult getJson1()
    {
        string result = "请求成功!";
        return Ok(result);
    }

    这里写图片描述

    NotFound()

    NotFound()方法会返回一个404的错误到客户端。

    [HttpGet]
    public IHttpActionResult getJson()
    {
        return NotFound();
    }

    这里写图片描述

    Content(HttpStatusCode statusCode, T value)

    向客户端返回值和http状态码。

    [HttpGet]
    public IHttpActionResult getJson()
    {
        return Content<string>(HttpStatusCode.OK, "OK");
    }

    这里写图片描述

    BadRequest()

    向客户端返回400的http错误。

    [HttpGet]
    public IHttpActionResult getJson2()
    {
        return BadRequest();
    }

    这里写图片描述

    Redirect(string location)

    将请求重定向到其他地方。

    [HttpGet]
    public IHttpActionResult getJson3()
    {
        return Redirect("http://localhost:7408/api/Values/getJson1");
    }
    [HttpGet]
    public IHttpActionResult getJson1()
    {
        string result = "请求成功!";
        return Ok(result);
    }

    这里写图片描述

    HttpResponseMessage

    HttpResponseMessage这个对象,表示向客户端返回一个http响应的消息对象(包含http状态码和需要返回客户端的消息)。这个对象也有它独特的使用场景:需要向客户端返回HttpResponse时就要用到这个对象。以导出为例,由于需要将导出的Excel文件输出到客户端浏览器,Webapi的服务端需要向Web的客户端输出文件流,这个时候一般的IHttpActionResult对象不方便解决这个问题,于是HttpReponseMessage派上了用场。

    public HttpResponseMessage Export()
    {
        //取数据
        var lstRes = OrderBLL.Export();
    
        //向Excel里面填充数据
        HSSFWorkbook workbook = new HSSFWorkbook();
        CreateAndFillSheet(workbook, lstRes);
    
        //保存到服务
        var fileName = "Excel" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
        var strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data" + fileName);
        using (FileStream fs = new FileStream(strPath, FileMode.Create))
        {
            workbook.Write(fs);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
            }
        }
    
        //输出到浏览器
        try
        {
            var stream = new FileStream(strPath, FileMode.Open);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            };
    
            return response;
        }
        catch
        {
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }

    自定义类型

    你也可以将webapi的接口和普通方法一样,返回任意的类型,WebApi会自动序列化你自定义任何返回类型,然后将序列化的值写到响应正文里,状态码统一返回200。

    [HttpGet]
    public object getJson()
    {
        var list = new List<userinfo>();
        list.Add(new userinfo { Name = "work", age = 11 });
        list.Add(new userinfo { Name = "hard", age = 12 });
        return list;
    }

    这里写图片描述

  • 相关阅读:
    Java实现 LeetCode 697 数组的度(类似于数组的map)
    Java实现 LeetCode 697 数组的度(类似于数组的map)
    Java实现 LeetCode 697 数组的度(类似于数组的map)
    Java实现 LeetCode 696 计数二进制子串(暴力)
    Java实现 LeetCode 696 计数二进制子串(暴力)
    Java实现 LeetCode 696 计数二进制子串(暴力)
    Java实现 LeetCode 695 岛屿的最大面积(DFS)
    Java实现 LeetCode 695 岛屿的最大面积(DFS)
    PHP serialize() 函数
    PHP print_r() 函数
  • 原文地址:https://www.cnblogs.com/hnsongbiao/p/9375888.html
Copyright © 2011-2022 走看看