使用HttpClient C#发送带有文件的嵌套JSON

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

我想将此对象发送到服务器:

public class Product
    {
        public string name { get; set; }
        public string description { get; set; }        
        public ICollection<Photo> photos { get; set; }

    }

此对象具有其他对象的集合:

public class Photo
    {
        public string url { get; set; }
        public IFormFile file { get; set; }
        public string description { get; set; }
    }

如何发送Product对象及其Photo对象的集合?以及如何在Photo对象中发送文件?(我想使用application/json而不是form-data

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

您应该将文件内容作为Base64字符串发送

创建这样的字符串

Byte[] bytes = File.ReadAllBytes("path\\to\\file.jpg");
String 64string = Convert.ToBase64String(bytes);

然后只需更新您的照片班级,以使该文件具有一个字符串,就可以为其分配它

public class Photo
{
    public string url { get; set; }
    public String fileContents { get; set; }
    public string description { get; set; }
}

Photo p = new Photo() { url = "...", fileContents = 64String, ..... }

当然,这是假设您的服务器期望这样做并且可以相应地解码!我假设您也在编写服务器端代码。

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