zoukankan      html  css  js  c++  java
  • webapi的返回类型,webapi返回图片

    1.0 首先是返回常用的系统类型,当然这些返回方式不常用到。如:int,string,list,array等。这些类型直接返回即可。

    1 public List<string> Get()
    2         {
    3             List<string> list = new List<string>() { "11","22","33"};
    4             return list;
    5         }

    1.1 用不同的浏览器测试发现,返回的类型竟然是不一样的。如用ie,edge返回的是json,而用chrome,firefox返回的是xml类型。后来才知道原来WebApi的返回值类型是根据客户端的请求报文头的类型而确定的。IE在发生http请求时请求头accpet节点相比Firefox和Chrome缺少"application/xml"类型,由于WebAPI返回数据为xml或json格式,IE没有发送可接受xml和json类型,所以默认为json格式数据,而Firefox和chrome则发送了可接受xml类型。请参考:http://www.cnblogs.com/lzrabbit/archive/2013/03/19/2948522.html

    2.0 返回json类型数据。这也是最常用的方式。

    1 public HttpResponseMessage Get()
    2         {
    3             var jsonStr = "{"code":0,"data":"abc"}";
    4             var result = new HttpResponseMessage(HttpStatusCode.OK)
    5             {
    6                 Content = new StringContent(jsonStr, Encoding.UTF8, "text/json")
    7             };
    8             return result;
    9         }

    3.0 返回流类型数据,如:图片类型。

     1 public HttpResponseMessage Get()
     2         {
     3             var imgPath = System.Web.Hosting.HostingEnvironment.MapPath("~/111.jpg");
     4             //从图片中读取byte
     5             var imgByte = File.ReadAllBytes(imgPath);
     6             //从图片中读取流
     7             var imgStream = new MemoryStream(File.ReadAllBytes(imgPath));
     8             var resp = new HttpResponseMessage(HttpStatusCode.OK)
     9             {
    10                 Content = new StreamContent(imgStream)
    11                 //或者
    12                 //Content = new ByteArrayContent(imgByte)
    13             };
    14             resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    15             return resp;
    16         }
  • 相关阅读:
    【OpenStack】OpenStack系列16之OpenStack镜像制作
    【OpenStack】OpenStack系列15之OpenStack高可用详解
    【OpenStack】OpenStack系列14之Dashboard定制开发
    【OpenStack】OpenStack系列13之Nova源码解析与API扩展
    linux之scp命令
    阿里大鱼短信平台
    count(1)与count(*)
    java中枚举类到高级使用
    idea中mybatis-plugin破解
    mmall项目之问题一(mavenplugin问题)
  • 原文地址:https://www.cnblogs.com/renjing/p/webapi-img.html
Copyright © 2011-2022 走看看