Reputation: 449
I am trying to return a list of objects that come from a database call that look like this:
public class ObjectA
{
public int Id { get; set; }
public string Name { get; set; }
public ObjectB ObjB { get; set; }
}
public class ObjectB
{
public int Id { get; set; }
public string Field { get; set; }
}
Call to get item from database in web api
[HttpGet]
public List<ObjectA> GetObjects([FromUri] int id)
{
var objs= objectRepo.All.Where(x => x.Id== id).ToList();
return objs;
}
Call from HTTPCLIENT
HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri("http://localhost:2478/api/controller/");
var result= client.GetAsync("GetObjects?id=" + 5);
Is there a better way to set up the get method? And how would the returned results be used once retrieved using httpclient?
I don't need to object B as an object belonging to object A but I do need the field from object B.
Upvotes: 0
Views: 825
Reputation: 6623
From the comments:
is it okay to return a list of objects like that?
If you have control over the API and if you just need the ObjectB
from your ObjectA
, then I would suggest you to change the API to return just ObjectB
s or even just the Field
from ObjectB
. For example:
objectRepo.All.Where(x => x.Id == id).Select(x => x.ObjB).ToList();
which will return a list of ObjectB
s.
should the parameter be passed into the Uri and not from the body if that's possible
Yes, it can be passed in the URI using [HttpGet("{id}")]
.
In the end you will have:
[HttpGet("{id}")]
public List<ObjectB> GetObjects(int id)
{
return objectRepo.All.Where(x => x.Id == id).Select(x => x.ObjB).ToList();
}
Upvotes: 1