Skip to main content
 首页 » 编程设计

c#之在没有 base64 编码的情况下通过 https 发送字节数组的方法

2024年02月20日10mfryf

我的 outlook 插件通过 https 发送大文件。目前,我在客户端使用 Convert.ToBase64String(),在 IIS 端的 http 处理程序上使用 Convert.FromBase64String()。

这已经出现了一些性能问题,而且我也在通过 SSL 保护数据,所以我真的想问是否有任何方法可以通过 https 转换字节数组而不使用会降低接收方 cpu 性能的编码结束。

我的客户代码:

string requestURL = "http://192.168.1.46/websvc/transfer.trn"; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
 
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on  the handler. 
string requestParameters = @"fileName=" + fileName + @"&secretKey=testKey=" + @"&currentChunk=" + i + @"&totalChunks=" + totalChunks + @"&smGuid=" + smGuid + 
                            "&data=" + HttpUtility.UrlEncode(Convert.ToBase64String(bytes)); 
 
// finally whole request will be converted to bytes that will be transferred to HttpHandler 
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters); 
 
request.ContentLength = byteData.Length; 
 
Stream writer = request.GetRequestStream(); 
writer.Write(byteData, 0, byteData.Length); 
writer.Close(); 
// here we will receive the response from HttpHandler 
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()); 
string strResponse = stIn.ReadToEnd(); 
stIn.Close(); 

存在性能问题的服务器代码:

byte[] buffer = Convert.FromBase64String(context.Request.Form["data"]); //  

请您参考如下方法:

您不必使用 contentType application/x-www-form-urlencoded 发送。为什么不设置为类似 application/octet-stream 的内容,设置内容长度并将数据直接复制到请求流中?只要您在另一端正确解释它,您就会没事。