Z.V
Z.V

Reputation: 1471

HttpGet to return image and Id

I have a function below that is used to return image and id. When testing I couldn't see my id being returned, instead, i can only see the image being returned in my browser (possibly due to it is entirely byte data).

            int id = 0;
            using (Bitmap bitmap = Image.Generate(context, out id))
            {
                HttpResponse response = context.Response;
                response.CacheControl = "no-cache";
                response.ContentType = "image/JPG";
                bitmap.Save(response.OutputStream, ImageFormat.Jpeg);
                response.End();

                var responseModel = new ResponseModel
                {
                    Id = id,
                    Image = bitmap
                };

                return Ok(responseModel);
            };

Response preview in chrome: enter image description here

Is this the appropriate way to return a response if there is an image included? If so, how do I get this response data from a ajax call, including the image and the ID (can it be done with Json.parse? but this is bytedata)?

Upvotes: 0

Views: 548

Answers (1)

Isaac Levin
Isaac Levin

Reputation: 2899

One thing you could do is add the Id in the header of HttpResponseMessage like this answer

Asp.net Web API return File with metadata about the file

I am on mobile so I will update my answer later but essentially you would just have the image be the body of the message and any metadata in the header. Then on client just parse out the response header to get what you need. I have used this in the past.

Sample as promised

public HttpResponseMessage Get()
{
    XDocument xDoc = GetXMLDocument();
    int id = CallToGetMyId();

    var response = this.Request.CreateResponse(
        HttpStatusCode.OK, 
        xDoc.ToString(), 
        this.Configuration.Formatters.XmlFormatter
    );
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "image.png"
    };
    response.Headers.Add("Id", id);
    return response;
}

Upvotes: 1

Related Questions