Adds support for json in multipart/form-data requests.
- Simple add this to your
ConfigureServices
services.AddJsonMultipartFormDataSupport(JsonSerializerChoice.Newtonsoft);
Or manually:
- Binder
services
.AddMvc(
properties => {
// ...
properties.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider()); // Here
}
)
- Operation filter
services.AddSwaggerGen(c => {
c.OperationFilter<MultiPartJsonOperationFilter>();
});
- Add to your
Controller
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Post([FromForm] MultipartFormData<Product> multiPartData) {
var file = multiPartData.File;
var product = multiPartData.Json;
}
or
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Post([FromForm] MultipartRequiredFormData<Product> multiPartData) {
var file = multiPartData.File;
var product = multiPartData.Json;
}
Or you can create your on wrapper
public class MyWrapper {
[FromJson] // <-- This attribute is required for binding.
public MyModel Json { get; set; }
public IFormFile File { get; set; }
}
and then
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Post([FromForm] MyWrapper myWrapper) {
// code
}
Notes:
It automatically adds examples from class which implements IExampleProvider<MyModel>
.