我的 C# 应用程序将文件上传到某些 API,我正在使用多部分请求,即我正在上传文件的 json 字符串和二进制文件,它适用于大多数文件,但对于极少数文件,它会给出异常,我的意思是让我们试试对于名为myFile128MB.dat
我得到异常的文件:
::: 将内容复制到流时出错。::: 无法从传输连接读取数据:发送或接收数据的请求被禁止,因为套接字已经在该方向上被先前的关闭调用关闭。::: System.Net.Http.HttpRequestException:将内容复制到流时出错。---> System.IO.IOException: Unable to read data from the transport connection: 发送或接收数据的请求被禁止,因为套接字已经在之前的关闭调用中关闭了该方向。---> System.Net.Sockets.SocketException: 不允许发送或接收数据的请求,因为套接字已经在 System.Net.Sockets.Socket.BeginReceive(Byte[ ] 缓冲区,Int32 偏移量,Int32 大小,SocketFlags socketFlags,
我的代码大致如下:
public async Task<Dictionary<string , string>> Upload(string filePath)
{
var fi = new FileInfo(FilePath);
var jsonString = "some json string";
var fileContents = File.ReadAllBytes(fi.FullName);
var webService = new Uri(url);
var requestMessage = new HttpRequestMessage(HttpMethod.Post , webService);
requestMessage.Method = HttpMethod.Post;
requestMessage.Headers.Add("Authorization" , "MyKey1234");
const string boundry = "------------------My-Boundary";
var multiPartContent = new MultipartFormDataContent(boundry);
var byteArrayContent = new ByteArrayContent(fileContents);
multiPartContent.Add(byteArrayContent);
var.Content = multiPartContent;
var httpClient = new HttpClient();
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage , HttpCompletionOption.ResponseContentRead , CancellationToken.None);
//exception in this line ^
return new Dictionary<string , string>();
}
呼叫者,召集者:
myDictionary = await Upload(filePath);
控制台应用程序的结构如下:
public class Program
{
public static void Main(string[] args) => MainAsync().Wait();
private static async Task MainAsync() => new MyClass().Start();
}
而里面MyClass:
public async void Start() => myDictionary = await Upload(filePath);