我正在尝试在继承 ASP.Net 4.5 中的 ApiController 的 valuecontroller 类中设置响应头 (Content-Type)
最终我希望在有人调用该 API 时在浏览器中呈现图像。目前它在浏览器中显示字节数组的 json 或 xml,我认为如果我正确设置了 content-Type 那么它应该可以工作。
我已经尝试过
public byte[] Get(int id)
{
var context = HttpContext.Current;
string filePath = "https://www.w3schools.com/tags/img_girl.jpg";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
Byte[] b = ImageToBinary(filePath); // Getting Byte array of a image file
HttpContext.Current.Response.Headers.Add("Content-Type", "image/jpeg"); // this does not works
HttpContext.Current.Response.ContentType = "image/jpeg"; // this also does not works
return b;
}
public static byte[] ImageToBinary(string imagePath)
{
byte[] buffer = null;
HttpWebRequest wrGETURL = (HttpWebRequest)WebRequest.Create(imagePath);
using (System.Net.HttpWebResponse webresponse = (HttpWebResponse)wrGETURL.GetResponse())
{
string ct = webresponse.ContentType;
Stream objStream = webresponse.GetResponseStream();
using (BinaryReader breader = new BinaryReader(objStream))
{
buffer = breader.ReadBytes((int)webresponse.ContentLength);
}
}
return buffer;
}