Using the .NET 6 Minimal API, I'm trying to handle multipart/form-data
in the POST method. However, with the following code:
app.MapPost("/tickets", async (IFreshdeskApiService s, [FromForm] CreateTicketDto dto) => await s.Add(dto))
.Accepts<CreateTicketDto>("multipart/form-data");
I'm receiving 400 Bad Request with body:
{
"error": "Expected a supported JSON media type but got \"multipart/form-data; boundary=--------------------------391539519671819893009831\"."
}
I switched to the non-minimal API (i.e. using app.MapControllers()
), but is there any way to handle this in minimal API?
CodePudding user response:
Please see the Explicit Parameter Binding section of
Personally, I would remove the [FromForm]
attribute from the endpoint, however, in my testing it works with or without it. The above technique will work with class
types too, not just record
s.
Simpler alternative
A simpler implementation is to pass HttpContext
into the action and read all values from the ctx.Request.Form
collection. In this case your action might look something like the following:
app.MapPost("/tickets", (HttpContext ctx, IFreshdeskApiService s) =>
{
// read value from Form collection
int.TryParse(ctx.Request.Form["Id"], out var id);
var name = ctx.Request.Form["Name"];
var status = ctx.Request.Form["Status"];
var dto = new CreateTicketDto(id, name, status);
s.Add(dto);
return Results.Accepted(value: dto);
});