繁体   English   中英

C# - 使用 RestRequest 在 http 请求的正文中发送文件

[英]C# - Send a file in the body of an http request using RestRequest

我尝试在 POST http 请求的正文中发送 xlsx 文件(来自路径)。 我能够发送文件,但它作为损坏的文件到达。(我无法尝试检查 api 上的问题,因为它是 api 等亚马逊等)这是我试过的代码:

    public async Task<string> PostPostman()
        {
         try
            {
                string filePath = @"D:\example2.xlsx";

                FileStream fs = File.OpenRead(filePath);
                var streamContent = new StreamContent(fs);
                streamContent.Headers.Add("Content-Type", "application/xlsx");
                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", streamContent.ReadAsStringAsync().Result, ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }

我发现问题是ReadAsStringAsync()打开了文件但没有关闭它。

我找到的解决方案是使用File.ReadAllBytes(filePath)发送文件,该文件读取文件并将其关闭。

这是最终代码:

public async Task<string> PostPostman()//found the code from the postman request I sent
        {
            try
            {
                string filePath = @"D:\example2.xlsx";

                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", File.ReadAllBytes(filePath), ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM