ASP.NET Core MVC 2
我需要将二进制数据发送到服务器。数据大小通常很大但不超过1 Gb。这是我尝试这样做的:
var client = new HttpClient();
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
fs.Position = 0;
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int) fs.Length);
ByteArrayContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Headers.ContentLength = fs.Length;
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/Home/Upload");
request.Content = content;
try
{
HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine("Response status code: {0}", response.StatusCode);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
在调试模式下,我尝试发送27Mb数据。在行
HttpResponseMessage response = await client.SendAsync(request);
断点有效,但在此之后没有任何事情发生:
的断点Console.WriteLine("Response status code: {0}", response.StatusCode);
和
Console.WriteLine("Exception: {0}", ex.Message);
不行。应用程序默默完成。
我做错了什么?
答案 0 :(得分:1)
无需使用ByArrayContent
,只需将StreamContent
与PostAsync
一起使用。
删除以下代码
fs.Position = 0;
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int) fs.Length);
ByteArrayContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Headers.ContentLength = fs.Length;
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/Home/Upload");
request.Content = content;
try
{
HttpResponseMessage response = await client.SendAsync(request);
替换为以下代码,HttpClient
包含PostAsync
我们可以使用
try
{
HttpResponseMessage response = await client.PostAsync("http://localhost:5000/Home/Upload", new StreamContent(fs));