API 内容类型更改为不同内容后,控制器不断返回 JSON

API controller keeps returning JSON after content type is changed to something different

我正在编写一个 API 控制器并试图将它 return 成一个 jpg 文件。然而,即使内容类型设置为 "application/jpg",我的回复消息仍在 return a 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;
    }

调用控制器之后就是这样 returns:

{
    "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
}

当调用网络 API 时,响应将始终在 JSON 中(这就是 HttpResponseMessages 的工作方式)。如果您想通过 API 发送图像,最简单的两种方法是将 link 发送到图像(如果图像是托管的),或者首先将图像转换为字节数组,例如所以:

 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);
        var memoryStream = new MemoryStream();
        image.Save(memoryStream, ImageFormat.Jpeg);
        result.Content = new ByteArrayContent(memoryStream.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    }

    return result;
}

然后在你的客户端你可以使用这样的东西:

        var x = await client.GetAsync("Image");

        using (var memoryStream = new MemoryStream(x.Content.ReadAsByteArrayAsync().Result))
        {
            Image returnImage = Image.FromStream(memoryStream);
        }