C# Post数据或文件到指定的服务器进行接收

简介: C# Post数据或文件到指定的服务器进行接收

应用场景

不同的接口服务器处理不同的应用,我们会在实际应用中将A服务器的数据提交给B服务器进行数据接收并处理业务。

比如我们想要处理一个OFFICE文件,由用户上传到A服务器,上传成功后,由B服务器负责进行数据处理和下载工作,这时我们就需要 POST A服务器的文件数据到B服务器进行处理。

实现原理

将用户上传的数据或A服务器已存在的数据,通过form-data的形式POST到B服务器,B服务由指定ashx文件进行数据接收,并转由指定的业务逻辑程序进行处理。如下图:

实现代码

PostAnyWhere类

创建一个 PostAnyWhere 类,

该类具有如下属性:

(1)public string PostUrl     要提交的服务器URL

(2)public List<PostFileItem> PostData   要准备的数据(PostFileItem类可包括数据和文件类型)

该类包含的关键方法如下:

(1)public void AddText(string key, string value)

        该方法将指定的字典数据加入到PostData中

(2)public void AddFile(string name, string srcFileName, string desName, string contentType = "text/plain")

        该方法将指定的文件添加到PostData中,其中 srcFileName 表示要添加的文件名,desName表示接收数据生成的文件名

(3)public string Send()

        该方法将开始POST传送数据

代码如下:

    public class PostAnyWhere
    {
        public string PostUrl { get; set; }
        public List<PostFileItem> PostData { get; set; }
 
        public PostAnyWhere()
        {
            this.PostData = new List<PostFileItem>();
        }
 
        public void AddText(string key, string value)
        {
            this.PostData.Add(new PostFileItem { Name = key, Value = value });
        }
 
        public void AddFile(string name, string srcFileName, string desName,string at, string contentType = "text/plain")
        {
            string[] srcName = Path.GetFileName(srcFileName).Split('.');
            string exName = "";
            if (srcName.Length > 1)
            {
                exName = "."+srcName[srcName.Length-1];
            }
            
            this.PostUrl = "https://www.xxx.com/test.ashx?guid=" + desName;
            ReadyFile(name, GetBinaryData(srcFileName), exName,contentType);
        }
         void ReadyFile(string name, byte[] fileBytes, string fileExName = "", string contentType = "text/plain")
        {
            this.PostData.Add(new PostFileItem
            {
                Type = PostFileItemType.File,
                Name = name,
                FileBytes = fileBytes,
                FileName = fileExName,
                ContentType = contentType
            });
        }
 
        public string Send()
        {
            var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            var request = (HttpWebRequest)WebRequest.Create(this.PostUrl);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
 
            Stream memStream = new System.IO.MemoryStream();
            var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
 
            var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
 
            var formFields = this.PostData.Where(m => m.Type == PostFileItemType.Text).ToList();
            foreach (var d in formFields)
            {
                var textBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, d.Name, d.Value));
                memStream.Write(textBytes, 0, textBytes.Length);
            }
 
            const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            var files = this.PostData.Where(m => m.Type == PostFileItemType.File).ToList();
            foreach (var fe in files)
            {
                memStream.Write(boundarybytes, 0, boundarybytes.Length);
                var header = string.Format(headerTemplate, fe.Name, fe.FileName ?? "System.Byte[]", fe.ContentType ?? "text/plain");
                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                memStream.Write(fe.FileBytes, 0, fe.FileBytes.Length);
            }
            memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            request.ContentLength = memStream.Length;
 
            HttpWebResponse response;
 
            try
            {
                using (var requestStream = request.GetRequestStream())
                {
                    memStream.Position = 0;
                    var tempBuffer = new byte[memStream.Length];
                    memStream.Read(tempBuffer, 0, tempBuffer.Length);
                    memStream.Close();
                    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                }
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException webException)
            {
                response = (HttpWebResponse)webException.Response;
            }
 
            if (response == null)
            {
                throw new Exception("HttpWebResponse is null");
            }
 
            var responseStream = response.GetResponseStream();
            if (responseStream == null)
            {
                throw new Exception("ResponseStream is null");
            }
 
            using (var streamReader = new StreamReader(responseStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
 
    public class PostFileItem
    {
        public PostFileItem()
        {
            this.Type = PostFileItemType.Text;
        }
 
        public PostFileItemType Type { get; set; }
        public string Value { get; set; }
        public byte[] FileBytes { get; set; }
        public string Name { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
    }
 
    public enum PostFileItemType
    {
        Text = 0,
        File = 1
    }
    public byte[] GetBinaryData(string filename)
    {
      if(!File.Exists(filename))
      {
        return null;
      }
      try
      {
        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        byte[] imageData = new Byte[fs.Length];
        fs.Read( imageData, 0,Convert.ToInt32(fs.Length));
        fs.Close();
        return imageData;
      }
      catch(Exception)
      {
        return null;
      }
      finally
      {
        
      }
    }   

ashx文件部署

在B服务器上部署ashx文件接收数据,ashx程序即,一般处理程序(HttpHandler),一个httpHandler接受并处理一个http请求,需要实现IHttpHandler接口,这个接口有一个IsReusable成员,一个待实现的方法ProcessRequest(HttpContextctx) 。.ashx程序适合产生供浏览器处理的、不需要回发处理的数据格式。

示例代码如下:

<%@ WebHandler Language="C#" Class="Handler" %>
 
using System;
using System.Web;
using System.IO;
 
public class Handler : IHttpHandler {
    
public void ProcessRequest (HttpContext context) {
   if (context.Request.Files.Count > 0)
   {
      string strPath = System.Web.HttpContext.Current.Server.MapPath("~/app_data/test/");
      string strName = context.Request.Files[0].FileName;
      string ext=Path.GetExtension(strName);
      string filename =HttpContext.Current.Request.QueryString["guid"].ToString()+Path.GetFileNameWithoutExtension(strName);
      if(ext!=""){
         filename = filename  + ext;
      }
      context.Request.Files[0].SaveAs(System.IO.Path.Combine(strPath, filename));
   }
}
 
public bool IsReusable {
   get {
      return false;
   }
}
 
}

小结

ashx处理接收的数据后,后续还需要配合实际的接口功能继续处理应用。另外,对于ashx页面,实际的应用则需要使用安全访问控制,只有正常登录或提供合法访问令牌的用户才可以进行访问。

以上代码仅供参考,欢迎大家指正,再次感谢您的阅读!

相关文章
|
11月前
|
Python
使用Python实现multipart/form-data文件接收的http服务器
至此,使用Python实现一个可以接收 'multipart/form-data' 文件的HTTP服务器的步骤就讲解完毕了。希望通过我的讲解,你可以更好地理解其中的逻辑,另外,你也可以尝试在实际项目中运用这方面的知识。
510 69
|
物联网 数据处理 C#
C#实现上位机开发,串口通信,读写串口数据并处理16进制数据
C#实现上位机开发,串口通信,读写串口数据并处理16进制数据。在自动化、物联网以及工业控制行业中,上位机开发是一项重要的技能。本教程主要介绍使用C#进行上位机开发,重点在于串口通信和数据处理。
2557 82
|
12月前
|
存储 安全 Linux
CentOS 7.9系统备份:每日定期发送最新备份文件到另一台服务器。
注意,这个解决方案忽略了很多细节,例如错误处理和通知、备份版本控制、循环处理旧的备份文件等等。此外,你也应该尽量保持源服务器和目标服务器之间快速,稳定且安全的网络连接,并且目标服务器应该有足够的空间用于存放每天的备份文件。如果你需要更高级的备份解决方案,可能需要考虑一下使用专门的备份工具或者服务。
549 18
|
开发框架 .NET Java
C#集合数据去重的5种方式及其性能对比测试分析
C#集合数据去重的5种方式及其性能对比测试分析
251 11
|
开发框架 .NET Java
C#集合数据去重的5种方式及其性能对比测试分析
C#集合数据去重的5种方式及其性能对比测试分析
257 10
|
设计模式 API C#
C# 一分钟浅谈:GraphQL 服务器端实现
本文通过C#语言从零开始构建一个简单的GraphQL服务器端实现,介绍了环境准备、项目创建、定义Schema、配置GraphQL等步骤。同时,探讨了常见问题如数据源问题、类型定义不一致、性能问题和权限控制,提供了相应的解决方法。希望帮助读者更好地理解和应用GraphQL。
219 3
|
网络协议 Ubuntu Linux
gpg从公钥服务器接收失败(gpg: keyserver receive failed: Server indicated a failure)
通过上述步骤,大多数情况下应该能够解决GPG从公钥服务器接收失败的问题。如果问题依旧存在,可能需要进一步调查与公钥服务器相关的更深层次的技术问题,或者考虑在相关社区论坛寻求帮助。
3514 1
|
SQL 缓存 分布式计算
C#如何处理上亿级数据的查询效率
C#如何处理上亿级数据的查询效率
405 2
|
6月前
|
XML 前端开发 C#
C#编程实践:解析HTML文档并执行元素匹配
通过上述步骤,可以在C#中有效地解析HTML文档并执行元素匹配。HtmlAgilityPack提供了一个强大而灵活的工具集,可以处理各种HTML解析任务。
323 19
|
7月前
|
监控 算法 C#
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
1342 0

热门文章

最新文章