原文: 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;
}