【发布时间】: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,而不是实际图像。
-
GetStudentImages与GetStudents有什么关系? -
GetStudentImages 仅检索图像,而 GetStudents 检索与学生相关的所有数据。
标签: asp.net-mvc image asp.net-web-api bytearray httpresponsemessage