我正在编写API控制器,并试图使其返回jpg文件。但是,即使内容类型设置为“ application / jpg”,我的响应消息仍在继续返回json。
public HttpResponseMessage Get()
{
var path = @"C:\Temp\Sample\background.jpg";
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/jpg");
result.Content.Headers.ContentType.MediaType = "application/jpg";
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "background.jpg"
};
stream.Close();
return result;
}
调用控制器后,它返回的是:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"Key": "Content-Type",
"Value": [
"application/jpg"
]
},
{
"Key": "Content-Disposition",
"Value": [
"attachment; filename=background.jpg"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
当调用Web API时,响应将始终为JSON(这就是HttpResponseMessages的工作方式)。如果要通过API发送图像,则两种最简单的方法是发送指向图像的链接(如果托管图像),或者首先将图像转换为字节数组,如下所示:
public HttpResponseMessage Get()
{
var path = @"C:\Temp\Sample\background.jpg";
var result = new HttpResponseMessage(HttpStatusCode.OK);
using(var stream = new FileStream(path, FileMode.Open)){
var image = Image.FromStream(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
}
return result;
}
然后在您的客户端上,您可以使用类似以下的内容:
using (var memoryStream = new MemoryStream(YourReceivedByteArray))
{
return Image.FromStream(memoryStream);
}