I'm trying to do a POST request with multipart/form-data from an Angular 6 application to a REST service in ASP.NET Core, but I have a Error 500. I tried too many solutions, but nothing worked. I tried to execute the request on Postman and get the same problem, but I tried in other software called ARC (Advanced REST Client) and works like a charm and I don't have any idea why.
On the server-side, I getting InvalidDataException: Missing content-type boundary. In my project, I'm using swagger too
here is my code
The request in angular:
public uploadPlanilha(planilha: File, idLote: number): Observable<Array<RequisicaoComposicao>>{
let formData = new FormData();
formData.append('arquivo', planilha, planilha.name);
formData.append('idLote', idLote.toString());
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.set("Content-Type", "multipart/form-data");
return this.httpClient.post<Array<RequisicaoComposicao>>(`${this.API_URL}requisicoes/upload`, formData, {
headers: httpHeaders
});
}
The controller method in Web Api
[HttpPost]
[Route("upload")]
[Consumes("multipart/form-data")]
[DisableRequestSizeLimit]
public ActionResult<List<RequisicaoComposicao>> PostPlanilhaRequisicoes([FromForm]ArquivoDto arquivoDto)
{
try
{
using (Stream arquivoPlanilha = arquivoDto.Arquivo.OpenReadStream())
{
List<RequisicaoComposicao> requisicaoComposicoes = _composicaoGestor.Inserir(arquivoPlanilha, int.Parse(arquivoDto.IdLote));
return Ok(requisicaoComposicoes);
}
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
The ArquivoDto class
public class ArquivoDto
{
public IFormFile Arquivo { get; set; }
public string IdLote { get; set; }
}
HttpHeadersis immutable, you need to set the header likelet httpHeaders = new HttpHeaders().set("Content-Type", "multipart/form-data").set("Accept", "multipart/form-data");otherwise each time you callseta new instance ofHttpHeadersis returned and your previous header is overwritten . That's why you are not getting thecontent-typeheader at the server.let httpHeaders = new HttpHeaders().set("Content-Type", "multipart/form-data"), you can't re-assign the httpHeaders variable.[FromForm]then the Content-Type should beapplication/x-www-url-formencoded, but if you only want to post the file then remove[FromForm]and use(IFormFile arquivoDto)as the parameter, the content-type should bemultipart/form-datain this case