webapi的返回类型,webapi返回图片

时间:2023-03-09 09:22:55
webapi的返回类型,webapi返回图片

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

 public List<string> Get()
{
List<string> list = new List<string>() { "","",""};
return list;
}

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;
}