欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)Post數(shù)據(jù)或文件到指定的服務(wù)器進(jìn)行接收

 更新時(shí)間:2024年03月01日 11:10:36   作者:初九之潛龍勿用  
這篇文章主要為大家詳細(xì)介紹了如何通過C#實(shí)現(xiàn)Post數(shù)據(jù)或文件到指定的服務(wù)器進(jìn)行接收,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考下

應(yīng)用場景

不同的接口服務(wù)器處理不同的應(yīng)用,我們會(huì)在實(shí)際應(yīng)用中將A服務(wù)器的數(shù)據(jù)提交給B服務(wù)器進(jìn)行數(shù)據(jù)接收并處理業(yè)務(wù)。

比如我們想要處理一個(gè)OFFICE文件,由用戶上傳到A服務(wù)器,上傳成功后,由B服務(wù)器負(fù)責(zé)進(jìn)行數(shù)據(jù)處理和下載工作,這時(shí)我們就需要 POST A服務(wù)器的文件數(shù)據(jù)到B服務(wù)器進(jìn)行處理。

實(shí)現(xiàn)原理

將用戶上傳的數(shù)據(jù)或A服務(wù)器已存在的數(shù)據(jù),通過form-data的形式POST到B服務(wù)器,B服務(wù)由指定ashx文件進(jìn)行數(shù)據(jù)接收,并轉(zhuǎn)由指定的業(yè)務(wù)邏輯程序進(jìn)行處理。如下圖:

實(shí)現(xiàn)代碼

PostAnyWhere類

創(chuàng)建一個(gè) PostAnyWhere 類,

該類具有如下屬性:

(1)public string PostUrl     要提交的服務(wù)器URL

(2)public List<PostFileItem> PostData   要準(zhǔn)備的數(shù)據(jù)(PostFileItem類可包括數(shù)據(jù)和文件類型)

該類包含的關(guān)鍵方法如下:

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

該方法將指定的字典數(shù)據(jù)加入到PostData中

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

該方法將指定的文件添加到PostData中,其中 srcFileName 表示要添加的文件名,desName表示接收數(shù)據(jù)生成的文件名

(3)public string Send() 

該方法將開始POST傳送數(shù)據(jù)

代碼如下:

    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服務(wù)器上部署ashx文件接收數(shù)據(jù),ashx程序即,一般處理程序(HttpHandler),一個(gè)httpHandler接受并處理一個(gè)http請(qǐng)求,需要實(shí)現(xiàn)IHttpHandler接口,這個(gè)接口有一個(gè)IsReusable成員,一個(gè)待實(shí)現(xiàn)的方法ProcessRequest(HttpContextctx) 。.ashx程序適合產(chǎn)生供瀏覽器處理的、不需要回發(fā)處理的數(shù)據(jù)格式。

示例代碼如下:

<%@ 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;
   }
}
 
}

小結(jié) 

ashx處理接收的數(shù)據(jù)后,后續(xù)還需要配合實(shí)際的接口功能繼續(xù)處理應(yīng)用。另外,對(duì)于ashx頁面,實(shí)際的應(yīng)用則需要使用安全訪問控制,只有正常登錄或提供合法訪問令牌的用戶才可以進(jìn)行訪問。

到此這篇關(guān)于C#實(shí)現(xiàn)Post數(shù)據(jù)或文件到指定的服務(wù)器進(jìn)行接收的文章就介紹到這了,更多相關(guān)C# Post數(shù)據(jù)或文件到指定服務(wù)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C# SkinEngine控件 給窗體添加皮膚的方法

    C# SkinEngine控件 給窗體添加皮膚的方法

    我在網(wǎng)上搜索過,給窗體使用皮膚的方法有很多,不過C#中這種方法最簡單。利用 IrisSkin2.dll 所提供的控件 SkinEngine 來為窗體添加皮膚。
    2013-04-04
  • C# GroupBy的基本使用教程

    C# GroupBy的基本使用教程

    這篇文章主要給大家介紹了關(guān)于C# GroupBy的基本使用教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • C#圖像處理之霓虹效果實(shí)現(xiàn)方法

    C#圖像處理之霓虹效果實(shí)現(xiàn)方法

    這篇文章主要介紹了C#圖像處理之霓虹效果實(shí)現(xiàn)方法,可實(shí)現(xiàn)圖片轉(zhuǎn)換成霓虹效果的功能,需要的朋友可以參考下
    2015-04-04
  • c# 應(yīng)用事務(wù)的簡單實(shí)例

    c# 應(yīng)用事務(wù)的簡單實(shí)例

    這篇文章介紹了c# 應(yīng)用事務(wù)的簡單實(shí)例,有需要的朋友可以參考一下
    2013-09-09
  • C#實(shí)現(xiàn)餐廳管理系統(tǒng)

    C#實(shí)現(xiàn)餐廳管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)餐廳管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • c#繼承與多態(tài)使用示例

    c#繼承與多態(tài)使用示例

    繼承是面向?qū)ο蟪绦蛟O(shè)計(jì)的主要特征之一,允許重用現(xiàn)有類去創(chuàng)建新類的過程。下面使用示例學(xué)習(xí)一下c#繼承與多態(tài)
    2014-01-01
  • 詳解C#中委托的概念與使用

    詳解C#中委托的概念與使用

    委托這個(gè)名字取的神乎其神的,但實(shí)質(zhì)是函數(shù)式編程,把函數(shù)作為參數(shù)傳遞給另一個(gè)參數(shù)。這篇文章主要為大家介紹一下C#中委托的概念與使用,需要的可以參考一下
    2023-02-02
  • C++實(shí)現(xiàn)日期類的示例詳解

    C++實(shí)現(xiàn)日期類的示例詳解

    這篇文章主要為大家詳細(xì)介紹了四個(gè)C++常用的日期類的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C++有一定的幫助,需要的可以參考一下
    2023-02-02
  • c# 生成隨機(jī)時(shí)間的小例子

    c# 生成隨機(jī)時(shí)間的小例子

    這篇文章介紹了c# 生成隨機(jī)時(shí)間的小例子,有需要的朋友可以參考一下
    2013-08-08
  • selenium.chrome寫擴(kuò)展攔截或轉(zhuǎn)發(fā)請(qǐng)求功能

    selenium.chrome寫擴(kuò)展攔截或轉(zhuǎn)發(fā)請(qǐng)求功能

    Selenium?WebDriver?是一組開源?API,用于自動(dòng)測(cè)試?Web?應(yīng)用程序,利用它可以通過代碼來控制chrome瀏覽器,今天通過本文給大家介紹selenium?chrome寫擴(kuò)展攔截或轉(zhuǎn)發(fā)請(qǐng)求功能,感興趣的朋友一起看看吧
    2022-07-07

最新評(píng)論