将文件上传从HTTPClient发送到dotnet核心应用程序

时间:2020-06-08 12:38:21

标签: c# .net-core dotnet-httpclient

我有一个使用dotnet核心控制器的服务器应用程序。那里有这个控制器:

        [HttpPost]
        [RequestSizeLimit(100_000)]
        public async Task<IActionResult> xxx([FromForm] string name, [FromForm] string description, [FromForm] bool isprivate, [FromForm] IFormFile icon)
{
   ...
}

当我从浏览器的前端发送请求时,它可以正常工作,并生成以下请求:

Frame 103: 2148 bytes on wire (17184 bits), 2148 bytes captured (17184 bits) on interface \Device\NPF_Loopback, id 2
Null/Loopback
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 51141, Dst Port: 8001, Seq: 4701, Ack: 1792, Len: 2064
Hypertext Transfer Protocol
    POST /api/xxx/xxxHTTP/1.1\r\n
    Host: localhost:8001\r\n
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0\r\n
    Accept: application/json, text/plain, */*\r\n
    Accept-Language: de,en-US;q=0.7,en;q=0.3\r\n
    Accept-Encoding: gzip, deflate\r\n
    Content-Type: multipart/form-data; boundary=---------------------------20261806215495369501698203786\r\n
    Content-Length: 1127\r\n
    Origin: http://localhost:8001\r\n
    DNT: 1\r\n
    Connection: keep-alive\r\n
    Referer: http://localhost:8001/xxx\r\n
     [truncated]Cookie: .AspNetCore.Cookies=CfDJ8M_ELI8knopFkQ6zEqeCkgwDf43UGRqyyzwLWbKrkSuSRcmzqAPIcsi94bVzQFVWJB0NOGVRZVgzm4n7sf-0ox3SPK1ChgaqQuPRTogxdWzbJZPo1DCCi1TMI04RH4tmMj8rgv8EwDko5s1S2BNw0Owj8qL_-loCOz2VYU7wG3lVl5TIVavb46_nV6_Zr6MVdz
    \r\n
    [Full request URI: http://localhost:8001/api/xxx/xxx]
    [HTTP request 6/6]
    [Prev request in frame: 97]
    [Response in frame: 107]
    File Data: 1127 bytes
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "---------------------------20261806215495369501698203786"
    [Type: multipart/form-data]
    First boundary: -----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part: 
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part: 
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part: 
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part:  (image/png)
    Last boundary: \r\n-----------------------------20261806215495369501698203786--\r\n

现在我也有一个使用HTTPClient用C#编写的客户端,并且我无法使fileupload正常工作。 这是我现在的代码:

        public async Task<string?> Addxxx(string name, string description, bool isPrivate, byte[] ImageData, CancellationToken token)
        {
            var url = $"{Scheme}://{Address}:{Port}/api/xxx/xxx";
            var Content = new MultipartFormDataContent();
            var ImageContent = new ByteArrayContent(ImageData);
            ImageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
            Content.Add(ImageContent);
            var request = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = new MultipartFormDataContent()
                {
                    {
                        new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
                        {
                            new KeyValuePair<string, string>("name" , name),
                            new KeyValuePair<string, string>("description" , description),
                            new KeyValuePair<string, string>("isprivate" , isPrivate.ToString()),
                        })
                    },
                    {Content }
                }
            };
            request.Headers.Add("Accept", "multipart/form-data");
            request.Headers.Add("User-Agent", UserAgent);
            request.Headers.Add("Cookie", Cookies);
            var response = await HttpClient.SendAsync(request, token);

            if (!response.IsSuccessStatusCode)
                return null;
            ...
        }

但是,这总是得到一个错误的请求。 这是生成的请求:

Frame 16: 1523 bytes on wire (12184 bits), 1523 bytes captured (12184 bits) on interface \Device\NPF_Loopback, id 2
Null/Loopback
Internet Protocol Version 4, Src: 192.168.2.101, Dst: 192.168.2.101
Transmission Control Protocol, Src Port: 51121, Dst Port: 8001, Seq: 1394, Ack: 1020, Len: 1439
Hypertext Transfer Protocol
    POST /api/xxx/xxxHTTP/1.1\r\n
    Host: 192.168.2.101:8001\r\n
    Accept: multipart/form-data\r\n
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36\r\n
     [truncated]Cookie: .AspNetCore.Cookies=CfDJ8M_ELI8knopFkQ6zEqeCkgx2TK33iweuVbSNkdR_HNs5nC6EEy6zFxnuwpIovyH9WenSzaVCDgW3VWk0BJJ7cDnfdnQ5W_o98sJvaVtiVmPk3JB8e5bySGdcoRN6NwIl27mqLMl89Kt5hnsrq5Jps9Q3kJ1XSk5kpMciycb9AijtG9N_tqqqhRbV9EvbQc0CUU
    Request-Id: |10c9eb89-46f0038fdc2e3b2d.\r\n
    Content-Type: multipart/form-data; boundary="4265ae7c-56da-4811-b646-fc1123794472"\r\n
    Content-Length: 576\r\n
    \r\n
    [Full request URI: http://192.168.2.101:8001/api/xxx/xxx]
    [HTTP request 3/3]
    [Prev request in frame: 10]
    [Response in frame: 20]
    File Data: 576 bytes
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "4265ae7c-56da-4811-b646-fc1123794472"
    [Type: multipart/form-data]
    First boundary: --4265ae7c-56da-4811-b646-fc1123794472\r\n
    Encapsulated multipart part:  (application/x-www-form-urlencoded)
    Boundary: \r\n--4265ae7c-56da-4811-b646-fc1123794472\r\n
    Encapsulated multipart part:  (multipart/form-data)
    Last boundary: \r\n--4265ae7c-56da-4811-b646-fc1123794472--\r\n

我做了很多尝试,但对于如何从客户端发送请求感到迷茫…… 有人可以向我指出如何与其他POST数据一起发送图像的正确方向吗?

0 个答案:

没有答案