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         }
posted @ 2016-09-22 18:12  一品码农  阅读(11359)  评论(2编辑  收藏  举报