【发布时间】:2017-09-11 18:55:53
【问题描述】:
我正在使用 MVC 和 C# 开发 Web API,我尝试返回存储在文件夹中的图像列表以及它们在数据库中的路径,我正在尝试:
public class Image {
public int Id { get; set; }
public string Path { get; set; }
public int Item_Id { get; set; }
public bool isMain { get; set; }
}
在图像控制器中我调用这个方法:
[HttpGet]
[ActionName("GetImageByItemId")]
public HttpResponseMessage GetImages(int id)
{
try
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Images.Where(e => e.Item_Id == id).ToList();
// ctx.Images.FirstOrDefault(e => e.Item_Id == id);
if (entity != null)
{
List<HttpResponseMessage> shapes = new List<HttpResponseMessage>();
HttpResponseMessage response = new HttpResponseMessage();
for (int i = 0; i < entity.Count; i++)
{
String filePath = HostingEnvironment.MapPath("~/Images/" + entity[i].Path + ".jpg");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
response.Content = new StreamContent(fileStream); // this file stream will be closed by lower layers of web api for you once the response is completed.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
shapes.Add(response);
}
// return response;
// return Request.CreateResponse(HttpStatusCode.OK, shapes);
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new {shapes});
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "The Images With ID" + id.ToString() + " Not Found");
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
如果我使用
return response;
或
return shapes[1];
返回一个图像是可行的,但我需要它返回一个图像列表,该怎么做?
【问题讨论】:
-
@SandRock 我不需要下载多个文件,我需要返回图像列表以在另一个使用此 wep API 的应用程序中显示它们。
标签: c# entity-framework asp.net-web-api