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;
        }
相关推荐
宋小黑22 分钟前
JDK 6到25 全版本网盘合集 (Windows + Mac + Linux)
java·后端
念何架构之路32 分钟前
Go进阶之panic
开发语言·后端·golang
先跑起来再说34 分钟前
Git 入门到实战:一篇搞懂安装、命令、远程仓库与 IDEA 集成
ide·git·后端·elasticsearch·golang·intellij-idea
码农阿豪1 小时前
Flask应用上下文问题解析与解决方案:从错误日志到完美修复
后端·python·flask
威迪斯特1 小时前
Flask:轻量级Web框架的技术本质与工程实践
前端·数据库·后端·python·flask·开发框架·核心架构
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于Springboot的扶贫众筹平台为例,包含答辩的问题和答案
java·spring boot·后端
程序员良许2 小时前
三极管推挽输出电路分析
后端·嵌入式
Java水解2 小时前
【JAVA 进阶】Spring AOP核心原理:JDK与CGLib动态代理实战解析
后端·spring
Java水解2 小时前
Spring Boot 4 升级指南:告别RestTemplate,拥抱现代HTTP客户端
spring boot·后端
宫水三叶的刷题日记2 小时前
工商银行今年的年终奖。。
后端