0

I need to pass an image within a json response. Here's my controller:

public IHttpActionResult GetStudents()
    {
        var data = db.Students.ToList();
        return Ok(data);
    }

That code obviously returns all the data for each student and returns the student_image column as varbinary but I need it to be passed as an image.

I can return the image if it's the only thing to be returned, and here's the code:

public HttpResponseMessage GetStudentImages(string id)
    {
        var img = (from s in db.Students select new { s.student_image, s.student_id }).Where(a => a.student_id == id).FirstOrDefault();
        var result = new HttpResponseMessage();

        if (img == null)
        {
            result.StatusCode = HttpStatusCode.NotFound;
        }
        else
        {
            result.Content = new ByteArrayContent(img.student_image);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        }
        return result;
    }

How can I pass the image inside the response ? Thanks.

4

1 回答 1

0

下面将返回一个 StudentModel 列表,该列表由Image包含每个图像字节数组的属性组成。

public class StudentModel
{
    public string Name { get; set; }
    public ImageModel Image { get; set; }
}

public class ImageModel
{
    public string ContentType { get; private set; }
    public byte[] Content { get; private set; }

    public ImageModel(string contentType, byte[] content)
    {
        ContentType = contentType;
        Content = content;
    }
}

public IHttpActionResult GetStudents()
{
    var data = db.Students.Select(
        student => new StudentModel
        {
            Name = student.Name,
            Image = new ImageModel("image/jpeg", student.student_image)
        }
    );
    return Ok(data);
}
于 2016-06-28T09:15:21.467 回答