使用HttpClient上传多部分表单文件

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

我正在尝试使用Support Bee API创建附件,如此处所述:https://supportbee.com/api#create_attachment

我编写了使用HttpClient创建并使用文件名发送请求的服务。

如果我在Postman中进行测试,它将成功。我使用form-data作为正文,只是选择要从UI上传的文件:

enter image description here

[当我尝试通过HttpClient服务上传它时不起作用:

public async Task<string> CreateAttachmentAsync(string fileName)
{
    // "client" is HttpClient provided via D.I.

    MultipartFormDataContent content = new MultipartFormDataContent();
    content.Add(new StreamContent(new FileStream(fileName, FileMode.Open)), "files[]");

    using (HttpResponseMessage response = await client.PostAsync(
        "https://xxx.supportbee.com/attachments?auth_token=xxx",
        content))
    {
        string responseString = await response.Content.ReadAsStringAsync();

        return responseString;
    }
}

这将导致500内部服务器错误。检查MultipartFormDataContent对象,我可以看到它的标题值是自动设置的:

{内容类型:多部分/表单数据; boundary =“ c9be3778-4de5-4460-9929-adcaa6bdda79”内容长度:164}

我还尝试过先将文件读取到字节数组,然后使用ByteArrayContent而不是StreamContent无效。响应没有提供任何帮助,但是由于请求在Postman中有效,因此我的代码肯定有问题,但是我不知道可以尝试什么。

c# dotnet-httpclient
1个回答
0
投票

当我的代码适用于邮递员,但不适用于我的项目时,我会这样做很多。

尝试为邮递员上的相同操作生成C#代码,将其与您自己的代码进行比较,看看您可能错过了什么。

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