Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a list of strings within a request?

Tags:

rest

c#

api

refit

I'm using Refit library for my app and I need to make a call to another service. I need to get all entities with ids that I'm passing.

I tried [Body] attribute and it still doesn't work. I manage to pass a request but the list if ids that another service gets is null while I'm definitely passing existing IEnumerable.

My IRefitProxy:

[Get("/students/allByIds")]
Task<IEnumerable<Student>> GetStudentsById(IEnumerable<string> ids);

Another service's API:

[RoutePrefix("api/students")]
[Route("allByIds")]
[HttpGet]
public IEnumerable<Student> AllByIds(IEnumerable<string> ids)
{
//ids here is null!

//call my repository blablabla
return students;
}

I pass an array/List of strings and it comes as null. The path is ok because I manage to fall into the method with breakpoint. How can I manage to pass it correctly?

like image 799
Sofia Bo Avatar asked Jan 27 '23 02:01

Sofia Bo


2 Answers

I managed to solve this question. Adding [Query(CollectionFormat.Multi)] solved the problem.

[Get("/students/allByIds")] Task<IEnumerable<Student>>GetStudentsById([Query(CollectionFormat.Multi)]IEnumerable<string> ids);

The receiving API needs to have [FromUri] attribute. Hope it helps someone!

like image 178
Sofia Bo Avatar answered Jan 29 '23 21:01

Sofia Bo


Not sure how you are calling your API's endpoint. But have you tried using the FromUri attribute within your method's parameters?

[Get("/students/allByIds")]
Task<IEnumerable<Student>> GetStudentsById([FromUri] IEnumerable<string> ids);

You should then be able to do call like so:

?ids=11&ids=12&ids=13

Or even pass an array of strings via JavaScript.

like image 43
MalvEarp Avatar answered Jan 29 '23 21:01

MalvEarp