Search code examples
asp.net-corepostmanmultipartform-datamultipart

Receiving multipart form-data json parameter null


I am trying to receive a multipart request from Postman containg 3 parameters:

  • An int
  • A file
  • A Json

I receive in the controller both the file and the integer fine, but the json has all the fields as null. What could be wrong ?

Json

    [Serializable]
    public class ProcessingRecipe
    {
        [JsonPropertyName("fileId")]
        public string FileID { get; set; }
        [JsonPropertyName("srcLang")]
        public string SrcLang { get; set; }

    }

Controller

    [HttpPost]
    [Route(Routes.Routes.File.PROCESS)]
    public async Task<ActionResult<FileProcessResponse>> ProcessFileAsync([FromForm]IFormFile uploadFile,[FromForm] ProcessingRecipe recipe,[FromForm]int aa)
    {
             //the file is ok
            // the int is 33
    }

Postman

enter image description here

Update !!!!!

I have used according to this post to no avail:

Custom Binder

public class JsonModelBinder : IModelBinder {
    public Task BindModelAsync(ModelBindingContext bindingContext) {
        if (bindingContext == null) {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // Check the value sent in
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None) {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            // Attempt to convert the input value
            var valueAsString = valueProviderResult.FirstValue;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType);
            if (result != null) {
                bindingContext.Result = ModelBindingResult.Success(result);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }
}

Controller action

public async Task<ActionResult<FileProcessResponse>> ProcessFileAsync([FromForm]IFormFile uploadFile,[ModelBinder(typeof(JsonModelBinder))] ProcessingRecipe recipe)
        {
                 //the file is ok
                // the int is 33
        }

Solution

  • This is a definite duplicate of how to upload a file and json data in postman

    In your case, maybe you can try something like what is suggested in the following(https://stackoverflow.com/a/52748531/11226302)