在 .NET 中将 http 请求添加到 multipart/mixed 请求

Add http requests to multipart/mixed request in .NET

我正在尝试在 C# .NET
中创建内容类型为 Multipart/mixed 的 POST 请求 Refer this

到目前为止,我已经尝试构建 HttpRequestMessage 类型的 POST 请求并将其添加到 MultipartContent 实例,但是 MultipartContent.add() 方法不接受 HttpRequestMessage 类型

如何将 http 请求添加到 .NET 5.0.0 preview-7 中的 multipart/mixed 请求?

我想它可以像这样但是我没有合适的服务器无法测试

C# 8.0、.NET Core 3.1 控制台应用程序(与 .NET 5 兼容)

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        string textPlain = "Hello World!";
        string textJson = "{ \"message\" : \"Hello World!\" }";

        using MixedContentList contentList = new MixedContentList
        {
            new StringContent(textPlain, Encoding.UTF8, "text/plain"),
            new StringContent(textJson, Encoding.UTF8, "application/json")
        };

        using Stream fileStream = File.OpenRead("pic1.jpg");
        HttpContent streamContent = new StreamContent(fileStream);
        streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = "pic1.jpg" };
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        contentList.Add(streamContent);

        try
        {
            string result = await PostMixedContentAsync("https://myserver.url", contentList);
            // success, handle result
            Console.WriteLine(result);
        }
        catch (Exception ex)
        {
            // failure
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }

    private static async Task<string> PostMixedContentAsync(string url, MixedContentList contentList)
    {
        using MultipartContent mixedContent = new MultipartContent();
        foreach (HttpContent content in contentList)
        {
            mixedContent.Add(content);
        }
        using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Content = mixedContent;

        //Console.WriteLine(request.ToString());
        //Console.WriteLine(await mixedContent.ReadAsStringAsync());
        //return "ok";

        using HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

public class MixedContentList : List<HttpContent>, IDisposable
{
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private bool disposed;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                foreach (HttpContent content in this)
                {
                    content?.Dispose();
                }
                Clear();
            }
            disposed = true;
        }
    }
}

带有未注释调试代码的输出

Method: POST, RequestUri: 'https://myserver.url/', Version: 1.1, Content: System.Net.Http.MultipartContent, Headers:
{
  Content-Type: multipart/mixed; boundary="3e48b0d7-82c0-4d64-9946-b6eadae9c7d6"
}
--3e48b0d7-82c0-4d64-9946-b6eadae9c7d6
Content-Type: text/plain; charset=utf-8

Hello World!
--3e48b0d7-82c0-4d64-9946-b6eadae9c7d6
Content-Type: application/json; charset=utf-8

{ "message" : "Hello World!" }
--3e48b0d7-82c0-4d64-9946-b6eadae9c7d6
Content-Disposition: form-data; filename=pic1.jpg
Content-Type: image/jpeg

<JPEG BINARY DATA HERE>
--3e48b0d7-82c0-4d64-9946-b6eadae9c7d6--

更新

由于 MultipartContent 不支持 application/http,您可以实现自己的源自 HttpContent 的内容,例如名为BatchContent,可以产生由MultipartContent组成的application/http。目标是获得所需的 ReadAsStringAsync() 输出。

请注意,Batch 可以将您绑定到 HTTP/1.1,但不支持 HTTP/2。还是提前想好了。[​​=22=]