Search code examples
c#restasp.net-apicontroller

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


I'm writing an API controller and am attempting to have it return a jpg file. However even though the content type is set to "application/jpg", my response message is continuing to 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;
    }

After calling the controller this is what it 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
}

Solution

  • When calls are made to a web API the responses will always be in JSON (Thats just how HttpResponseMessages work). If you want to send an image via your API the two easiest methods are to either send a link to the image (if the image is hosted), or to first convert the image into a byte array like so:

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

    And then on your client side you can use something like this:

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