C#代码,postman请求直接输出文件相关代码

代码如下

C# 复制代码
    public class DownloadWaybillModel
    {
        /// <summary>
        /// 类型:Parent Waybills,Shipment Ref,Child Waybills
        /// </summary>
        public string WayBillType { get; set; }
        /// <summary>
        /// 运单号,多个用逗号隔开
        /// </summary>
        public string WayBills { get; set; }
        /// <summary>
        ///  默认值:LC WB
        /// </summary>
        public string PrintOption { get; set; }
    }
C# 复制代码
  [HttpPost]
        public ActionResult LCDownloadPDF2(DownloadWaybillModel model)
        {

            string postUrl = baseurl + "DownloadWaybill";
            Dictionary<string, string> headers = new Dictionary<string, string>();
            string base64Str = ToBase64AndToken(username, password);
            string body = JsonConvert.SerializeObject(model);
                try
                    {
                       var httpClient = new HttpClient();
        
                        // 设置超时时间
                        httpClient.Timeout = TimeSpan.FromSeconds(30000);
        
                        var request = new HttpRequestMessage
                        {
                            Method = HttpMethod.Post,
                            RequestUri = new Uri(postUrl),
                            Content = new StringContent(body, Encoding.UTF8, "application/json")
                        };
      headers.Add("Authorization", base64Str.Replace("=",""));
                    //    request.Headers.Add("Authorization", "dGVzdC5hcGlAbGluZWNsZWFyZXhwcmVzcy5jb218QVBJbGluZWNsZWFyIzU1OTB8U2pPSm1XSTBjeDltSW4yZlQxTXFvaTVMUzVlZERPZEtrYTJONkx0ZEpxTm1ISXZuMHVvVHRpY1okVmliUUJKaA");
                    
                    httpClient.DefaultRequestHeaders.Accept.Add(
                           new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/pdf")
                        );
                        var response222 = httpClient.SendAsync(request).Result;

                        Stream pdfStream = response222.Content.ReadAsStreamAsync().Result; // 同步获取流

                        // 3. 设置响应头,确保 Postman 识别为 PDF
                        Response.ContentType = "application/pdf"; // 告诉 Postman 这是 PDF 类型
                        // 可选:设置为 attachment 触发下载,inline 尝试预览
                        Response.AddHeader("Content-Disposition", "inline; filename=\"test.pdf\"");

                        // 4. 将流直接写入响应输出(不转字符串)
                        pdfStream.CopyTo(Response.OutputStream); // 同步复制流到响应
                        Response.Flush();

                        return new EmptyResult();
                
                    }
                    catch (Exception ex)
                    {

                        return Json(new
                        {
                            respnonModelData = ex,
                            requestData = model
                        });
                    }
             
             
        }
C# 复制代码
        private string ToBase64AndToken(string username, string password)
        {
            string tempStr = username + "|" + password+"|"+APIToken;
            byte[] inputBytes = Encoding.UTF8.GetBytes(tempStr);
            string base64str = Convert.ToBase64String(inputBytes);
            return base64str;
        }

postman 请求和输出效果

这篇文章最主要想表达的两个地方。 一是 Authorization 对应的 值不能有=号,否则验证不通过。 二是,输出文件这段代码

C# 复制代码
     httpClient.DefaultRequestHeaders.Accept.Add(
                           new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/pdf")
                        );
                        var response222 = httpClient.SendAsync(request).Result;

                        Stream pdfStream = response222.Content.ReadAsStreamAsync().Result; // 同步获取流

                        // 3. 设置响应头,确保 Postman 识别为 PDF
                        Response.ContentType = "application/pdf"; // 告诉 Postman 这是 PDF 类型
                        // 可选:设置为 attachment 触发下载,inline 尝试预览
                        Response.AddHeader("Content-Disposition", "inline; filename=\"test.pdf\"");

                        // 4. 将流直接写入响应输出(不转字符串)
                        pdfStream.CopyTo(Response.OutputStream); // 同步复制流到响应
                        Response.Flush();

                        return new EmptyResult();

封装一层的代码

C# 复制代码
      [HttpPost]
        public ActionResult LCDownloadPDF(DownloadWaybillModel model)
        {

            string postUrl = baseurl + "DownloadWaybill";
            Dictionary<string, string> headers = new Dictionary<string, string>();
            string base64Str = ToBase64AndToken(username, password);
            headers.Add("Authorization", base64Str.Replace("=",""));
         
            string body = JsonConvert.SerializeObject(model);
            var response222 = HttpHelperService.HttpPost22(postUrl, body, "application/json", headers, 3000);

            Stream pdfStream = response222.Content.ReadAsStreamAsync().Result; // 同步获取流

            // 3. 设置响应头,确保 Postman 识别为 PDF
            Response.ContentType = "application/pdf"; // 告诉 Postman 这是 PDF 类型
            // 可选:设置为 attachment 触发下载,inline 尝试预览
            Response.AddHeader("Content-Disposition", "inline; filename=\"test.pdf\"");

            // 4. 将流直接写入响应输出(不转字符串)
            pdfStream.CopyTo(Response.OutputStream); // 同步复制流到响应
            Response.Flush();
            return new EmptyResult();
        }

请求方法

C# 复制代码
      public static HttpResponseMessage HttpPost22(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
        {
            body = body ?? "";
            SetCertificatePolicy();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                    return response;
                }
            }
        }
        
            /// <summary>
        /// 设置证书策略
        /// </summary>
        public static void SetCertificatePolicy()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
        }

        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
           object sender, X509Certificate cert,
            X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
相关推荐
行百里er4 小时前
Redis 完结篇——Redis 热点问题在 Spring Boot 项目中实战
redis·后端
高频因子挖掘机5 小时前
只取最近 60 个交易日,却每次拉全历史:量化脚本变慢的原因与改法
后端·github·api
孟健6 小时前
从5000亿Token到83%字节匹配:AI逆向工程与重构的工程闭环实践
后端·架构·ai编程
码事漫谈7 小时前
丢得静悄悄,谈一谈 Agent 的记忆是怎么没的
后端
迪飞特科技7 小时前
智慧物业平台实战:Spring Boot 整合小程序实现报修巡检费用全流程
spring boot·后端·小程序
考虑考虑7 小时前
@JsonInclude注解使用
spring boot·后端·spring
IT_陈寒7 小时前
Vite的这个问题坑了我三天,原来如此解决!
前端·人工智能·后端
网易云信7 小时前
大模型能上岗做销售吗?我们让 12 款国产模型交了 420 份作业
前端·后端
CCblandy7 小时前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构
蜗牛互联网8 小时前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python