1

I am trying to implment a file return GET on a webapi. With the end implementation being able to just add src in an image tag to the api get endpoint. i.e.

<img src='myapi/api/file/{id}' />

I have followed the following stack question;

Return an image using ASP.NET Web API and display it?

My controller code is as follows;

 [HttpGet]
    [ProducesResponseType(typeof(HttpResponseMessage), 200)]
    [Route("{id}")]
    public HttpResponseMessage Get(int id)
    {
        var response = _service.Get(id);

        HttpAssert.Success(response);
        HttpAssert.IsNotNull(response);

        var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(response.ByteArray);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue(response.MimeType);

        return result;

        // return Ok(response.Result);
    }

My service is returning the file as a byte array with the correct mime type association, however when I call this in postman or a web browser i get the following return;

{
"version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
},
"content": {
    "headers": [
        {
            "key": "Content-Type",
            "value": [
                "image/jpeg"
            ]
        }
    ]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true

}

Can anyone direct me as to what i am doing wrong here?

4
  • It seems to me that you don't want to return the image but rather the path of the image.
    – David
    Oct 30, 2018 at 10:11
  • No I want to return the image itself, so that the img tag can render the returned file. Oct 30, 2018 at 10:12
  • The src attribute of an img tag is for the path of an image. If I were looking to do what you are doing I might temporarily store the image (if it isn't stored already) and then provide the path to the image tag.
    – David
    Oct 30, 2018 at 10:21
  • In terms of what you're doing wrong, HttpResponseMessage does not work the same way in ASP.NET Core - it's not a supported return type, which means the MVC pipeline just serialises it as an object without special meaning. Oct 30, 2018 at 10:41

0

Browse other questions tagged or ask your own question.