ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# WebApi之接口返回类型详解

2022-07-21 13:33:08  阅读:212  来源: 互联网

标签:WebApi HttpGet return C# 详解 new IHttpActionResult public 客户端


转自:https://www.cnblogs.com/hnsongbiao/p/9375888.html  有补充     

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派上了用场。

前端人员取不到FileName,此处代码有补充:

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.Add("Access-Control-Expose-Headers", "Content-Disposition");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            //添加解决中文乱码
            FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8),
            DispositionType = "UTF-8"
        };
        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;
}

这里写图片描述

 

标签:WebApi,HttpGet,return,C#,详解,new,IHttpActionResult,public,客户端
来源: https://www.cnblogs.com/huishanlife/p/16501577.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有