将HTTP请求添加到.NET中的多部分/混合请求

问题描述

我正在尝试创建内容类型为:多部分/在C#.NET中混合的POST请求
Refer this

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

如何在 .NET 5.0.0 Preview-7 中的多部分/混合请求中添加http请求?

解决方法

我认为它可能看起来像这样,但由于没有合适的服务器,因此无法进行测试。

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,"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的名称,它可以产生由application/http组成的MultipartContent。目标是获得所需的ReadAsStringAsync()输出。

请注意,该批次可以将您绑定到HTTP/1.1,并且不支持HTTP/2。还是事先考虑一下。