【问题标题】:Add http requests to multipart/mixed request in .NET将 http 请求添加到 .NET 中的多部分/混合请求
【发布时间】:2020-08-18 20:20:44
【问题描述】:

我正在尝试使用 Content-Type: Multipart/mixed in C# .NET 创建一个 POST 请求
Refer this

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

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

【问题讨论】:

标签: c# .net .net-core .net-5


【解决方案1】:

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

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() 输出。

请注意,批处理可以将您绑定到HTTP/1.1,并且不支持HTTP/2。或者提前考虑一下。

【讨论】:

  • 您构建的multipart/mixed 请求在正文中不包含另一个Http 请求,如问题中提供的链接
  • @Anant_Kumar 啊,对不起。我错过了。看起来那是不可能的。但是您可以实现自己的HttpRequestMessage,它接受多个请求消息。但是为什么不单独发送那些POST 请求呢?
  • 如果您可以更新 MultipartContent 中无法进行 Http 请求的答案,我会接受它作为答案。我想在一批中捆绑多个 Http 请求(检查有问题的链接)
  • @Anant_Kumar 我有更好的主意,不要实现HttpRequestMessage,它可能太复杂但HttpContent 例如命名为BatchContent,接受由MultipartContent 组成的application/http 类型。目标是获得所需的ReadAsStringAsync() 输出。
  • @Anant_Kumar 请注意,批处理可以将您绑定到HTTP/1.1,并且不支持HTTP/2。或者提前考虑一下。
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 2017-06-17
  • 2017-02-15
相关资源
最近更新 更多