简体   繁体   English

通过 HtppClient Post 请求发送超过 1 个文件 c#

[英]Send more than 1 file over HtppClient Post request c#

I'm currently working with an API and I have to send files thanks to http post protocol.我目前正在使用 API,由于 http post 协议,我必须发送文件。

With postman, everithing works fine and I can send an array of files that can contains more than 1 file:使用 postman,一切正常,我可以发送一个包含多个文件的文件数组:

在此处输入图像描述

For that, I'm using HttpClient in my c# application, but I only can send one file.为此,我在我的 c# 应用程序中使用了 HttpClient,但我只能发送一个文件。 Moreover, my body must contains form-data body so I created a MultipartFormDataContent object for send my file.此外,我的正文必须包含表单数据正文,因此我创建了一个 MultipartFormDataContent object 来发送我的文件。

public async Task<SubmitIdentityResults> SubmitIdentity(Guid companyId, DocumentTypes docType, SubmitIdentityParameters submitIdentityParameters)
        {
            try
            {
                var accesstoken = await _authTokenFromClientID.GetAccessToken();
                var client = _httpClientFactory.CreateClient("MyClient");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accesstoken);


                MultipartFormDataContent form = new MultipartFormDataContent();
                form.Add(new StreamContent(submitIdentityParameters.File!), "Files", submitIdentityParameters.FileName!);

                var response = await client.PostAsync($"api/Document/{docType.ToString()}", form);

                if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
                {
                    return default(SubmitIdentityResults)!;
                }
                return await response.Content.ReadFromJsonAsync<SubmitIdentityResults>() ?? default(SubmitIdentityResults)!;

            }
            catch (Exception)
            {
                throw;
            }
        }

There is a way to develop the same bahaviour in c# with httpclient and mulitipartformdata?有一种方法可以在 c# 中使用 httpclient 和 mulitipartformdata 开发相同的行为吗?

I think you should pass an array SubmitIdentityParameters[] submitIdentityParameters and do like this.我认为你应该传递一个数组SubmitIdentityParameters[] submitIdentityParameters并这样做。

foreach (var file in submitIdentityParameters)
{
    form.Add(new StreamContent(file.File!), "Files", file.FileName!);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM