dmitry_dreko
dmitry_dreko

Reputation: 471

get json data and images

I have Web Api Controller which get list of cars from database

[HttpGet, Route("list")]
public object List()
{
    var cars = context.Cars.ToList();        
    return Json(cars);
}

Response looks like

[{
   "markName": "Chevrolet",
   "modelName": "Spark EV",
   "year": 2014,
   "id": 1
},
{
   "markName": "Chevrolet",
   "modelName": "Volt",
   "year": 2014,
   "id": 2
}]

Also I have a function to get image by 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");
        }

How can I get ALL data (json and images) in one request? Or i should do this some other way?

Upvotes: 3

Views: 1613

Answers (1)

Nkosi
Nkosi

Reputation: 247451

You can create a view model to encapsulate all the desired information. Include a url to where to get the image along with the other metadata

for example.

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

You would then include a link to the photo action

[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");
}

An example response could look like

[{
   "markName": "Chevrolet",
   "modelName": "Spark EV",
   "year": 2014,
   "id": 1,
   "photo": "cars/1/photo"
},
{
   "markName": "Chevrolet",
   "modelName": "Volt",
   "year": 2014,
   "id": 2
   "photo": "cars/2/photo"
}]

Upvotes: 2

Related Questions