Search code examples
c#formsfileasp.net-coremultipartform-data

Why IFormFile is null in nested object?


I've got these models

public sealed class UpdateFacilityReportFirstStepCommand : ICommand<ExecutionResult>
{
    // other props

    /// <summary>
    /// Gets or sets the hired staff.
    /// </summary>
    /// <value>The hired staff.</value>
    public List<HiredStaffUpsertModel> HiredStaff { get; set; } = new List<HiredStaffUpsertModel>();
}

public class HiredStaffUpsertModel
{
    // other props

    /// <summary>
    /// Gets or sets the insurance card file.
    /// </summary>
    /// <value>The insurance card file.</value>
    public HiredStaffCarInsuranceCardModel CarInsuranceCardFile { get; set; } = new HiredStaffCarInsuranceCardModel();
}

public class HiredStaffCarInsuranceCardModel
    {
        /// <summary>
        /// Gets or sets the file.
        /// </summary>
        /// <value>The file.</value>
        [FileValidator("pdf,doc,docx", 10 * 1024 * 1024, true)]
        public IFormFile File { get; set; }
    
        /// <summary>
        /// Gets or sets a value indicating whether this instance is changed.
        /// </summary>
        /// <value><c>true</c> if this instance is changed; otherwise, <c>false</c>.</value>
        public bool IsChanged { get; set; }
    }

And in my controller I'm expecting public [FromForm] UpdateFacilityReportFirstStepCommand command. That's how I send form in Postman (content-type: multipart/form-data): enter image description here

And that's what I get: enter image description here

I have no idea why my File is null, although bool IsChanged is received. My frontend developer said that he'll send me form keys like on the Postman screenshot, and I don't get why it works fine with primitive types and doesn't with files.


Solution

  • The way I found to solve it, it's same as yours.

    public class Purchase 
    {
        public string Customer { get; set; }
        public IEnumerable<Product> Products { get; set; }
    }
    
    public class Product
    {
        public string ProductCode { get; set; }
        public IFormFile ProductImage { get; set; }
    }
    

    You have to send it like Products[0].ProductImage, otherwise you'll get null in ProductImage.