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;
        }
相关推荐
回家路上绕了弯13 小时前
五分钟内重复登录 QQ 号定位:数据结构选型与高效实现方案
分布式·后端
AI三林叔13 小时前
第2章 MCP协议深度解析
后端
Felix_XXXXL13 小时前
Spring Security安全框架原理与实战
java·后端
JaguarJack13 小时前
从零开始打造 Laravel 扩展包:开发、测试到发布完整指南
后端·php·laravel
星释14 小时前
Rust 练习册 :Minesweeper与二维数组处理
开发语言·后端·rust
小蒜学长14 小时前
springboot基于Java的校园导航微信小程序的设计与实现(代码+数据库+LW)
java·spring boot·后端·微信小程序
微学AI14 小时前
基于openEuler操作系统的Docker部署与AI应用实践操作与研究
后端
王元_SmallA14 小时前
IDEA + Spring Boot 的三种热加载方案
java·后端
LCG元14 小时前
实战:用 Shell 脚本自动备份网站和数据库,并上传到云存储
后端
Yeats_Liao14 小时前
时序数据库系列(四):InfluxQL查询语言详解
数据库·后端·sql·时序数据库