轉載:http://www.itdos.com/Mvc/20150302/0741255.htmlhtml
using System.IO; /// <summary> /// WebApi返回圖片 /// </summary> public HttpResponseMessage GetQrCode() { var imgPath = @"D:\ITdosCom\Images\itdos.jpg"; //從圖片中讀取byte var imgByte = File.ReadAllBytes(imgPath); //從圖片中讀取流 var imgStream = new MemoryStream(File.ReadAllBytes(imgPath)); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(imgByte) //或者 //Content = new StreamContent(stream) }; resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); return resp; } /// <summary> /// WebApi返回json數據 /// </summary> public HttpResponseMessage GetQrCode() { var jsonStr = "{\"IsSuccess\":true,\"Data\":\"www.itdos.com\"}"; var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(jsonStr, Encoding.UTF8, "text/json") }; return result; } /// <summary> /// WebApi返回字符串 /// </summary> public HttpResponseMessage GetQrCode() { var str = "IT大師www.itdos.com"; var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(str, Encoding.UTF8, "text/plain") }; return result; }