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;
        }
相关推荐
h***67377 小时前
SpringBoot整合easy-es
spring boot·后端·elasticsearch
S***267513 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
@大迁世界15 小时前
相信我兄弟:Cloudflare Rust 的 .unwrap() 方法在 330 多个数据中心引发了恐慌
开发语言·后端·rust
5***g29815 小时前
新手如何快速搭建一个Springboot项目
java·spring boot·后端
2***B44916 小时前
Rust在系统编程中的内存安全
开发语言·后端·rust
U***e6316 小时前
Rust错误处理最佳实践
开发语言·后端·rust
q***471816 小时前
Spring中的IOC详解
java·后端·spring
码事漫谈17 小时前
C++小白最容易踩的10个坑(附避坑指南)
后端
码事漫谈18 小时前
性能提升11.4%!C++ Vector的reserve()方法让我大吃一惊
后端
稚辉君.MCA_P8_Java18 小时前
Gemini永久会员 Java中的四边形不等式优化
java·后端·算法