【问题标题】:Pass data with an image using web api使用 web api 通过图像传递数据
【发布时间】:2016-06-28 08:38:38
【问题描述】:

我需要在 json 响应中传递图像。 这是我的控制器:

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

该代码显然返回每个学生的所有数据并将 student_image 列作为 varbinary 返回,但我需要将其作为图像传递。

如果只返回图片,我可以返回,代码如下:

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

如何在响应中传递图像?谢谢。

【问题讨论】:

  • 您忘记在else 的开头添加以下内容:result = new HttpResponseMessage(HttpStatusCode.OK);
  • GetStudentImages 工作正常。问题是当我在列表中返回它时。
  • GetStudents 返回学生数据列表,包括图像,但它显示为 varbinary,而不是实际图像。
  • GetStudentImagesGetStudents 有什么关系?
  • GetStudentImages 仅检索图像,而 GetStudents 检索与学生相关的所有数据。

标签: asp.net-mvc image asp.net-web-api bytearray httpresponsemessage


【解决方案1】:

以下将返回一个 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多