.net 发布包含文件和文本的请求正文

gwbalxhn  于 2022-12-01  发布在  .NET
关注(0)|答案(1)|浏览(137)

在Windows应用程序中,我必须将文本文件上传到服务器,为此我使用了post API,在其中我必须传递file参数和text参数。
我已经尝试了MultipartFormDataContent做同样的事情,但是不知何故文件上传正在发生,参数没有通过请求主体。
附加 Postman 请求正文:

代码我已经尝试使用MultipartFormDataContent

RequestJson requestJson  = new RequestJson ();
requestJson.uploadFile = FilePath;  // string Path of file
requestJson.userName= "Nation";
requestJson.email = "Nation@xyz.com";

HttpContent postData = new StringContent(JsonConvert.SerializeObject(requestJson ), Encoding.Default, "application/octet-stream");
var content = new MultipartFormDataContent();
content.Add(postData, "upload", "file3.txt");

Task<HttpResponseMessage> message = client.PostAsync(ServerUrl, content);
k10s72fa

k10s72fa1#

相反,您必须将属性逐一添加到MultipartFormDataContent

content.Add(new StringContent(requestJson.email), "email");
content.Add(new StringContent(requestJson.userName), "userName");
content.Add(/* File Content */, "uploadFile", "file3.txt");

您可以使用 * System.Reflection * 来迭代RequestJson类中的每个属性,如下所示:

using System.Reflection;

foreach (PropertyInfo prop in typeof(RequestJson).GetProperties(BindingFlags.Instance|BindingFlags.GetProperty|BindingFlags.Public))
{
    if (prop.Name == "uploadFile")
    {
        var fileContent = /* Replace with Your File Content */;

        content.Add(fileContent, prop.Name, "file3.txt");
    }
    else
    {
        content.Add(new StringContent(JsonConvert.SerializeObject(prop.GetValue(requestJson))), prop.Name);
    }
}

Demo @ .NET Fiddle

相关问题