I tried using Refit with multipart/form-data and a list of objects and I can’t get the list back.
Here is an example of what I’ve done:
I created a Refit interface for my API, I have a route that uses multipart/form-data:
[HttpPost]
public async Task<ActionResult<Guid>> CreateRecipe([FromForm] CreateRecipeRequest request)
{
var result = await _mediator.Send(new CreateRecipeCommand(request);
return result.IsSuccess ? Ok(result.Value) : result.ToProblemDetails();
}
As you can see I use a [FromForm]
because in my request I use an IFormFile
:
public class CreateRecipeRequest
{
public string Name { get; set; }
public List<IngredientRequest> Ingredients { get; set; }
public IFormFile Image { get; set; }
}
On the Refit side, the interface looks like this:
public interface IRecipesApi
{
[Multipart]
[Post("/api/Recipes")] Task<ApiResponse<Guid>> CreateRecipe([AliasAs("Name")] string name, [AliasAs("Ingredients")] List<IngredientRequest> ingredients, [AliasAs("Image")] StreamPart image);
}
Next I create a Refit client:
var recipesApi = RestService.For<IRecipesApi>(httpClient);
var stream = File.Open(Path.Combine(Directory.GetCurrentDirectory(), "0.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read);
var streampart = new StreamPart(stream, "photo.jpg", "image/jpeg");
var ingredients = new List<IngredientRequest>()
{
new IngredientRequest()
{
Name = "Tomato"
Quantity = 1,
},
new IngredientRequest()
{
Name = "Mozzarella"
Quantity = 1,
},
};
var response = await recipesApi.CreateRecipe("Tomato and mozzarella", ingredients, streampart);
The call arrives well to the route, however the list of ingredients is not filled.
Do you know how to solve this problem?
Thanks