I have been struggling for the past three days trying to send serialized json of a complex type (DTO object called fileItem) and IFormFile type named as file to one of my API which accepts two inputs, a FileItem object and IFormFile object.
But I keep getting an error "Unsupported Media Type". Note that when I send only file or only object then to API end point by updating the endpoint to accept either file only or complexType only, then it works fine, but if I am sending both together, then I get that "Unsupported Media Type" error which is already available in the request I am sending
Please guide me in a proper direction your help will be really appreciated.
ASP.NET MVC web app
public async Task<string> SaveFiles(FileItem _fileItem2, IFormFile _file)
{
using (var multipartFormContent = new MultipartFormDataContent())
{
var fileItem = new StringContent(
JsonSerializer.Serialize(_fileItem2), Encoding.UTF8, Application.Json);
multipartFormContent.Add(fileItem, "fileItem");
// Add the file
var fileStreamContent = new StreamContent(_file.OpenReadStream());
fileStreamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(_file.ContentType);
multipartFormContent.Add(fileStreamContent, name: "file", _file.FileName);
// Method 1 : this method returns Unsupported media type, but if file is removed then it works fine.
var response = await httpClient.PostAsync("/Upload/SaveFileWithData", multipartFormContent);
// Method 2 : this method also returns Unsupported media type, but if file is removed then it works fine.
var request = new HttpRequestMessage(HttpMethod.Post, "/Upload/SaveFileWithData");
request.Content = multipartFormContent;
var responsemsg = await httpClient.SendAsync(request);
responsemsg.EnsureSuccessStatusCode();
return await responsemsg.Content.ReadAsStringAsync();
}
}
This is the .NET 6.0 Web API (above request we send to this api)
[HttpPost()]
[Route("SaveFileWithData")]
public async Task<string> SaveFileWithData(FileItem? fileItem, IFormFile? file)
{
int i = 2;
return "fileSavedSuccessfully";
}