我有Web Api Controller,可以从数据库中获取汽车列表
[HttpGet, Route("list")]
public object List()
{
var cars = context.Cars.ToList();
return Json(cars);
}
回复看起来像
[{
"markName": "Chevrolet",
"modelName": "Spark EV",
"year": 2014,
"id": 1
},
{
"markName": "Chevrolet",
"modelName": "Volt",
"year": 2014,
"id": 2
}]
我还有一个通过id
获取图像的功能[HttpGet, Route("{id}/photo")]
public IActionResult GetPhoto(int id)
{
string path = "blalblabla"
Byte[] b = System.IO.File.ReadAllBytes(path);
return File(b, "image/jpeg");
}
如何在一个请求中获取所有数据(json和图像)?或者我应该以其他方式做到这一点?
答案 0 :(得分:2)
您可以创建一个视图模型来封装所有需要的信息。包括一个URL到哪里获取图像以及其他元数据
例如。
null
然后,您将包含指向照片操作的链接
public class CarModel {
public string markName { get; set; }
public string modelName { get; set; }
public int year { get; set; }
public int id { get; set; }
public string photo { get; set; }
}
示例响应可能看起来像
[HttpGet("list")]
public IActionResult List() {
var cars = context.Cars.AsEnumerable();
var models = cars.Select(car =>
new CarModel {
markName = car.markName,
modelName = car.modelName,
year = car.year,
id = car.id,
photo = Url.RouteUrl("CarPhoto", new { id = car.id })
}).ToList();
return Ok(models);
}
[HttpGet("{id}/photo", Name = "CarPhoto")]
public IActionResult GetPhoto(int id) {
string path = "blalblabla"
Byte[] b = System.IO.File.ReadAllBytes(path);
return File(b, "image/jpeg");
}