I’m using ASP.NET Core Minimal API. I have an endpoint where I want to receive an IFormFile
along with a Dictionary<string, string>
property in the same request. I set the Accepts<TestDictionaryRequest>("multipart/form-data")
and use [FromForm]
on the handler parameter. Uploading the file works correctly, but the TestDictionary
property is always null, even when I set values in the Swagger UI.
Here is the code:
public class TestDictionaryRequest
{
public Dictionary<string, string> TestDictionary { get; set; }
public IFormFile TestFile { get; set; }
}
public class TestDictionaryEndpoint : IEndpoint
{
public void MapEndpoint(IEndpointRouteBuilder app)
{
app.MapPost("test/dictionary", Handler)
.DisableAntiforgery()
.WithTags("Test")
.Accepts<TestDictionaryRequest>("multipart/form-data");
}
public static IResult Handler([FromForm] TestDictionaryRequest request)
{
return Results.Ok(new
{
Dictionary = request.TestDictionary,
Count = request.TestDictionary?.Count ?? 0,
IsNull = request.TestDictionary == null
});
}
}
What additional steps or configuration are needed so that the Dictionary<string, string> TestDictionary
is bound correctly (not null) when using multipart/form-data
with IFormFile
in a Minimal API endpoint?
-
How are you trying the API call? With Postman, or directly with cUrl?Tasos K.– Tasos K.2025年09月15日 14:16:54 +00:00Commented Sep 15 at 14:16
-
Using swagger. And now I can that is a reason of error. Swagger attempts to send TestDictionary = {"additionalProp1":"string","additionalProp2":"string","additionalProp3":"string"} instead of sending each key-value like TestDictionary["additionalProp1"] = "string", etc.Dmytro Kotenko– Dmytro Kotenko2025年09月22日 18:14:14 +00:00Commented Sep 22 at 18:14
1 Answer 1
To bind form to dictionary the form keys should be in a specific format containing keys enclosed in []
(see for example tests in the ASP.NET Core github repo), i.e. for your model they should look like TestDictionary[some_key_here]
(i.e. TestDictionary[hello]
).
For example if posting via Postman:
Postman Minimal APIs Dictionary Form binding
Which will result in the data successfully parsed:
Minimal APIs Dictionary Form binding result
Minimal APIs Dictionary Form binding result
If you move the dictionary to the "root" handler:
static IResult Handler([FromForm] IDictionary<string, string> request, IFormFile testFile) =>
Then form keys should be like [some_key_here]
.
If the default binding convention is not working for you - you can always handle the raw form:
static IResult Handler(HttpRequest r)
{
var files = r.Form.Files;
var data = r.Form;
return Results.Ok(...);
}
Or do some custom binding for example via introducing BindAsync
method to your model.
Comments
Explore related questions
See similar questions with these tags.