目錄
應用場景
實現原理
實現代碼
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<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頁面,實際的應用則需要使用安全訪問控制,只有正常登錄或提供合法訪問令牌的用戶才可以進行訪問。
以上代碼僅供參考,歡迎大家指正,再次感謝您的閱讀!