必须使用 HttpClient C# 上传带有注册表单数据的图像

Posted

技术标签:

【中文标题】必须使用 HttpClient C# 上传带有注册表单数据的图像【英文标题】:Have to upload image with registration form data using HttpClient C# 【发布时间】:2021-06-02 16:32:15 【问题描述】:

我有 .Net Core 3.1 Api 端点,它将 UserData 作为 [FromForm]。

我也在这里上传图片,使用邮递员运行良好。图片上传和 UserData 插入数据库。

但是当我调用 HttpClint.PostAsync 时它不起作用,而我正在使用 MultipartFormDataContent();

API 的 EndPoing 签名:

public async Task<IActionResult> SaveUser([FromForm] UserData usr) 

Xamarin 端的图片上传代码:

  private async Task UploadFileMedia()
    
        Constant.mediaFile = null;
        await CrossMedia.Current.Initialize();
        Constant.mediaFile = await CrossMedia.Current.PickPhotoAsync();

        if (Constant.mediaFile is null)
            return;
    

Http 客户端命中:

var requestContent = new MultipartFormDataContent()
                    

                    new StringContent(JsonConvert.SerializeObject(dictionary), Encoding.UTF8, "application/json"),
                        new StreamContent(Constant. mediaFile.GetStream()),
                            "\"file\"",
                            $"\"Constant.mediaFile.Path\""
                    ;
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");


 var response = await client.PostAsync("api/user/save", requestContent);

【问题讨论】:

如果你可以让它在 Postman 中工作,Postman 有能力为你生成相应的 C# 代码 【参考方案1】:

如果您想同时向您的 ASP.NET Core API 后端发出图像文件和 json 数据的请求,您可以参考以下代码 sn-p。

requestContent.Add(new StringContent(JsonConvert.SerializeObject(dictionary), Encoding.UTF8, "application/json"), "Prop1");
requestContent.Add(new StreamContent(your_filestream_here), "file", System.IO.Path.GetFileName(filepath));


var response = await client.PostAsync("/api/user/save", requestContent);

UserData

public class UserData

    public string Prop1  get; set; 
    public IFormFile file  get; set; 

测试结果

【讨论】:

【参考方案2】:

您有一个属性 [FromForm] UserData usr,它接受类型 application/x-www-url-formencoded,但您将数据作为 application/json 发送,您需要将绑定属性更改为 [FromBody],您可以阅读这里的区别

What the difference between [FromForm] and [FromBody] in Asp.Net Core

当然还有official web site

【讨论】:

以上是关于必须使用 HttpClient C# 上传带有注册表单数据的图像的主要内容,如果未能解决你的问题,请参考以下文章

带有返回内容的 Task<string> 的 C# httpclient

如何使用 C# HttpClient PostAsync 显示上传进度

C#:带有 POST 参数的 HttpClient

如何使用 C# HttpClient 或 AWS SDK 通过 CloudFront 将视频上传到 S3

使用带有表单编码参数和标头的 C# httpclient 发布

C# Xamarin 文件上传到 API 可以使用 RestSharp,但不能使用 HttpClient