1. 程式人生 > >webapi的返回型別,webapi返回圖片

webapi的返回型別,webapi返回圖片

原文: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型別資料。這也是最常用的方式。

 public HttpResponseMessage Get()
         {
             var jsonStr = "{\"code\":0,\"data\":\"abc\"}";
             var result = new HttpResponseMessage(HttpStatusCode.OK)
             {
                 Content = new StringContent(jsonStr, Encoding.UTF8, "text/json
") }; return result; }

3.0 返回流型別資料,如:圖片型別。

 public HttpResponseMessage Get()
         {
             var imgPath = System.Web.Hosting.HostingEnvironment.MapPath("~/111.jpg");
             //從圖片中讀取byte
             var imgByte = File.ReadAllBytes(imgPath);
//從圖片中讀取流 var imgStream = new MemoryStream(File.ReadAllBytes(imgPath)); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(imgStream) //或者 //Content = new ByteArrayContent(imgByte) }; resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); return resp; }