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


    目录

    应用场景

    实现原理

    实现代码

    PostAnyWhere类

    ashx文件部署

    小结 


    应用场景

    不同的接口服务器处理不同的应用,我们会在实际应用中将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 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传送数据

    代码如下:

    1. public class PostAnyWhere
    2. {
    3. public string PostUrl { get; set; }
    4. public List PostData { get; set; }
    5. public PostAnyWhere()
    6. {
    7. this.PostData = new List();
    8. }
    9. public void AddText(string key, string value)
    10. {
    11. this.PostData.Add(new PostFileItem { Name = key, Value = value });
    12. }
    13. public void AddFile(string name, string srcFileName, string desName,string at, string contentType = "text/plain")
    14. {
    15. string[] srcName = Path.GetFileName(srcFileName).Split('.');
    16. string exName = "";
    17. if (srcName.Length > 1)
    18. {
    19. exName = "."+srcName[srcName.Length-1];
    20. }
    21. this.PostUrl = "https://www.xxx.com/test.ashx?guid=" + desName;
    22. ReadyFile(name, GetBinaryData(srcFileName), exName,contentType);
    23. }
    24. void ReadyFile(string name, byte[] fileBytes, string fileExName = "", string contentType = "text/plain")
    25. {
    26. this.PostData.Add(new PostFileItem
    27. {
    28. Type = PostFileItemType.File,
    29. Name = name,
    30. FileBytes = fileBytes,
    31. FileName = fileExName,
    32. ContentType = contentType
    33. });
    34. }
    35. public string Send()
    36. {
    37. var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
    38. var request = (HttpWebRequest)WebRequest.Create(this.PostUrl);
    39. request.ContentType = "multipart/form-data; boundary=" + boundary;
    40. request.Method = "POST";
    41. request.KeepAlive = true;
    42. Stream memStream = new System.IO.MemoryStream();
    43. var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    44. var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
    45. var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
    46. var formFields = this.PostData.Where(m => m.Type == PostFileItemType.Text).ToList();
    47. foreach (var d in formFields)
    48. {
    49. var textBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, d.Name, d.Value));
    50. memStream.Write(textBytes, 0, textBytes.Length);
    51. }
    52. const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    53. var files = this.PostData.Where(m => m.Type == PostFileItemType.File).ToList();
    54. foreach (var fe in files)
    55. {
    56. memStream.Write(boundarybytes, 0, boundarybytes.Length);
    57. var header = string.Format(headerTemplate, fe.Name, fe.FileName ?? "System.Byte[]", fe.ContentType ?? "text/plain");
    58. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    59. memStream.Write(headerbytes, 0, headerbytes.Length);
    60. memStream.Write(fe.FileBytes, 0, fe.FileBytes.Length);
    61. }
    62. memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
    63. request.ContentLength = memStream.Length;
    64. HttpWebResponse response;
    65. try
    66. {
    67. using (var requestStream = request.GetRequestStream())
    68. {
    69. memStream.Position = 0;
    70. var tempBuffer = new byte[memStream.Length];
    71. memStream.Read(tempBuffer, 0, tempBuffer.Length);
    72. memStream.Close();
    73. requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    74. }
    75. response = (HttpWebResponse)request.GetResponse();
    76. }
    77. catch (WebException webException)
    78. {
    79. response = (HttpWebResponse)webException.Response;
    80. }
    81. if (response == null)
    82. {
    83. throw new Exception("HttpWebResponse is null");
    84. }
    85. var responseStream = response.GetResponseStream();
    86. if (responseStream == null)
    87. {
    88. throw new Exception("ResponseStream is null");
    89. }
    90. using (var streamReader = new StreamReader(responseStream))
    91. {
    92. return streamReader.ReadToEnd();
    93. }
    94. }
    95. }
    96. public class PostFileItem
    97. {
    98. public PostFileItem()
    99. {
    100. this.Type = PostFileItemType.Text;
    101. }
    102. public PostFileItemType Type { get; set; }
    103. public string Value { get; set; }
    104. public byte[] FileBytes { get; set; }
    105. public string Name { get; set; }
    106. public string FileName { get; set; }
    107. public string ContentType { get; set; }
    108. }
    109. public enum PostFileItemType
    110. {
    111. Text = 0,
    112. File = 1
    113. }
    114. public byte[] GetBinaryData(string filename)
    115. {
    116. if(!File.Exists(filename))
    117. {
    118. return null;
    119. }
    120. try
    121. {
    122. FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
    123. byte[] imageData = new Byte[fs.Length];
    124. fs.Read( imageData, 0,Convert.ToInt32(fs.Length));
    125. fs.Close();
    126. return imageData;
    127. }
    128. catch(Exception)
    129. {
    130. return null;
    131. }
    132. finally
    133. {
    134. }
    135. }

    ashx文件部署

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

    示例代码如下:

    1. <%@ WebHandler Language="C#" Class="Handler" %>
    2. using System;
    3. using System.Web;
    4. using System.IO;
    5. public class Handler : IHttpHandler {
    6. public void ProcessRequest (HttpContext context) {
    7. if (context.Request.Files.Count > 0)
    8. {
    9. string strPath = System.Web.HttpContext.Current.Server.MapPath("~/app_data/test/");
    10. string strName = context.Request.Files[0].FileName;
    11. string ext=Path.GetExtension(strName);
    12. string filename =HttpContext.Current.Request.QueryString["guid"].ToString()+Path.GetFileNameWithoutExtension(strName);
    13. if(ext!=""){
    14. filename = filename + ext;
    15. }
    16. context.Request.Files[0].SaveAs(System.IO.Path.Combine(strPath, filename));
    17. }
    18. }
    19. public bool IsReusable {
    20. get {
    21. return false;
    22. }
    23. }
    24. }

    小结 

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

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

  • 相关阅读:
    js获取上周、本周、上月、本月、第一天和最后一天
    深度学习之路=====11=====>>ShuffleNet(tensorflow2)
    原生M1/M2 Photoshop 2022 for Mac(PS2022)v23.4.2 中英文正式发布详情介绍&安装教程
    Lambda表达式,Stream流
    爬山算法(Hill Climbing Algorithm)详细介绍
    Ceph qos 限速
    小结笔记:多位管理大师关于管理的要素的论述
    Bootstrap响应式轮播效果网页(1+X Web前端开发中级 例题)
    加速训练之并行化 tf.data.Dataset 生成器
    【矩阵论】2. 矩阵分解——正规谱分解——正规阵
  • 原文地址:https://blog.csdn.net/michaelline/article/details/136315275