Angular /.NET Core API-System.InvalidOperationException:'错误的Content-Type:应用程序/表单数据'

问题描述 投票:0回答:1

[当我尝试从Angular 9 WebApp将pdf发布到我的.NET Core API 3. +时,抛出以下错误:

“ System.InvalidOperationException:'错误的Content-Type:应用程序/表单数据'”

[当我使用邮递员和表格数据(选择文件:pdf)时,它可以很好地工作。但是我不能使其与Angular一起使用。有什么建议吗?

((我在Angular中使用jsPDF生成PDF,因为它很容易,并且我不想将它们存储在数据库中。我存储票证的QRCodeString等等,但不存储整个pdf文件。此方法仅适用于通过电子邮件发送pdf,所以让我想知道是否应该首先使用.NET API。不过,我还是想了解这个错误!)

C#

[Authorize]
[HttpPost("{batchId}/send/{toEmailAddress}")]
public ActionResult SendTicket([FromRoute] long batchId, [FromRoute] string toEmailAddress)
{
    MimeMessage message = new MimeMessage();

    MailboxAddress from = new MailboxAddress("someName", "[email protected]");
    MailboxAddress to = new MailboxAddress($"{toEmailAddress}");

    message.From.Add(from);
    message.To.Add(to);
    message.Subject = "someSubject";

    BodyBuilder builder = new BodyBuilder();
    builder.HtmlBody = "<h1>Hi!</h1>";

    //The Request.Form.Files is where the error gets thrown!
    foreach (var file in Request.Form.Files)
    {
        Image img = new Image();
        img.ImageTitle = file.FileName;

        MemoryStream ms = new MemoryStream();
        file.CopyTo(ms);
        img.ImageData = ms.ToArray();

        builder.Attachments.Add("PDF", img.ImageData, new ContentType("application", "pdf"));

        ms.Close();
        ms.Dispose();
    }

    message.Body = builder.ToMessageBody();

    SmtpClient client = new SmtpClient();
    client.Connect("smtp.gmail.com", 587, false);
    client.Authenticate("username", "password"); //Temporarily hardcoded
    client.Send(message);
    client.Disconnect(true);
    client.Dispose();

    return Ok();
}

Angular“ api.service.ts”

sendBatch = (batchId: number, toEmailAddress: string, formData: FormData) => {
    let reqHeader = new HttpHeaders({ 
      'Content-Type': 'application/form-data',
      'Authorization': 'Bearer ' + this.token.idToken
    });
    return this.http.post<any>(`${environment.apiUrl}/api/batches/${batchId}/send/${toEmailAddress}`, formData, {headers: reqHeader});
}

Angular“ batches.component.ts”

sendPdf = () => {
    //...
    const formData = new FormData();
    formData.append('pdf', doc);

    this.apiService.sendBatch(this.batchId, "[email protected]", formData).subscribe((data)=>{
      console.log(data);
    });
}
c# angular typescript asp.net-core-webapi asp.net-core-2.0
1个回答
0
投票

application/form-data不是有效的MIME类型。

我认为您可能会混淆application/x-www-form-urlencodedmultipart/form-data

粘一个。我看到您想添加带有pdf文件的零件。正确的MIME类型是multipart/form-data

© www.soinside.com 2019 - 2024. All rights reserved.