How to post form-data IFormFile with HttpClient?

后端 未结 4 1564
暖寄归人
暖寄归人 2021-01-04 07:22

I have backend endpoint Task Post(IFormFile csvFile) and I need to call this endpoint from HttpClient. Currently I am getting Unsuppor

4条回答
  •  有刺的猬
    2021-01-04 07:42

    This worked for me as a generic

    public static Task PostFormDataAsync(this HttpClient httpClient, string url, string token, T data)
        {
            var content = new MultipartFormDataContent();
    
            foreach (var prop in data.GetType().GetProperties())
            {
                var value = prop.GetValue(data);
                if (value is FormFile)
                {
                    var file = value as FormFile;
                    content.Add(new StreamContent(file.OpenReadStream()), prop.Name, file.FileName);
                    content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = prop.Name, FileName = file.FileName };
                }
                else
                {
                    content.Add(new StringContent(JsonConvert.SerializeObject(value)), prop.Name);
                }
            }
    
            if (!string.IsNullOrWhiteSpace(token))
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            return httpClient.PostAsync(url, content);
        }
    

提交回复
热议问题