Search code examples
c#.netasp.net-core.net-core

Unable to send a Multipart request with an Image and JSON using [FromForm]


I have a controller endpoint that I want to use for both uploading an image, and also sending a JSON payload.

I know in Spring boot you could use @RequestPart annotation and pass the key/value pair as form data. I'm using .net core but struggling to test sending a request to my endpoint.

My model class looks like this: CreateCompanyRequest.cs

public class CreateCompanyRequest {
    
    public string Name { get; set; }
    public string Description { get; set; }
    public CreateAddressRequest? Address { get; set; }
    public int IndustryId { get; set; }
    public int Size { get; set; }
    public DateTime FoundedDate { get; set; }
}

And I also have a wrapper class that contains this Request class, along with an IFormFile property to use for uploading a file.

CreateCompanyMultipartRequest.cs

public class CreateCompanyMultipartRequest {
    
    [FromForm(Name = "company")]
    public CreateCompanyRequest Company { get; set; }
    
    [FromForm(Name = "avatar")]
    public IFormFile Avatar { get; set; }
}

CompanyController.cs

     [Authorize(Roles = "Recruiter")]
        [HttpPost]
        public async Task<IActionResult> CreateCompany([FromForm] CreateCompanyMultipartRequest request) {
            
            var response = await _companyService.CreateCompany(request.Company, "[email protected]");
            
            if (response != null && request.Avatar != null) {
                await _documentService.UploadDocument(request.Avatar, DocumentType.AVATAR, "[email protected]", response.Id);
            }
            
           // Extra validation..

            return Ok(new ApiResponse<CompanyResponse>() {
                Data = response, Status = true
            });
        }

I tried sending the request in postman with the keys being Avatar and Company, which match the request class, but I get this validation error.

The data im sending for the Company is a json file with the required properties, also tried sending the json as a text type in Postman.

enter image description here


Solution

  • You could try post with json string and then deserialize to object in controller.

        public class CreateCompanyMultipartRequest
        {
            public string Company { get; set; }
    
            public IFormFile Avatar { get; set; }
        }
    
            [HttpPost]
            public async Task<IActionResult> CreateCompany([FromForm]CreateCompanyMultipartRequest request)
            {
                CreateCompanyRequest createCompanyRequest =JsonSerializer.Deserialize<CreateCompanyRequest>(request.Company);
                .....
            }
    

    enter image description here