Hello friends, today we will solve a little problem which a few people might encounter while building APIs in ASP.net core. This will be a very short post, since we will go straight to the point with the solution. We will see how to in ASP.net core upload files and json data for each file
You might come across a situation where you need to build an API to upload multiple files, and allow the users of the API to pass additional information associated to each of those files to your API. This post tells exactly how to do that.
To upload a single file, it is quite easy. To upload multiple files too. Now we want to upload files and json data for each file. To do that, follow these steps.
1 2 3 4 5 | public class MyFileAttributes { public double XAxis { get; set; } public double YAxis { get; set; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class FormDataJsonModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult != ValueProviderResult.None) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); var stringValue = valueProviderResult.FirstValue; var result = Newtonsoft.Json.JsonConvert.DeserializeObject(stringValue, bindingContext.ModelType); if (result != null) { bindingContext.Result = ModelBindingResult.Success(result); return Task.CompletedTask; } } return Task.CompletedTask; } } |
1 2 3 4 5 | public async Task<IActionResult> UploadFiles( [FromForm][ModelBinder(BinderType = typeof(FormDataJsonModelBinder))] IList<MyFileAttributes> fileAttributes, IList<IFormFile> files) { } |
1 | [{ "XAxis " : 70, "YAxis" : 347}, { "XAxis " : 10, "YAxis" : 200}] |
If you like this post, don’t hesitate to follow me on Twitter or Github and subscribe to this page’s notifications to stay updated with new articles or like my page on Facebook.
With this, you will be able to send files to your API and add information to them by simply passing an array of json data. This solution targets a small problem, but might be useful to a large number of people.
https://stackoverflow.com/questions/41367602/upload-files-and-json-in-asp-net-core-web-api
ASP.net Core Upload Files and Json Data For each file.
Follow me on social media and stay updated
Recent Comments