【问题标题】:Post big data through HTTP protocol通过HTTP协议发布大数据
【发布时间】:2018-03-29 19:29:55
【问题描述】:

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);

不工作。应用程序静默完成。

我做错了什么?

【问题讨论】:

  • 你是在服务器端接收数据吗?
  • 不,我的控制器的断点在这种情况下不起作用。但是如果我通过 Postman 程序发布相同的文件,那么服务器会收到它并且控制器的断点可以工作。我不明白这种行为差异。
  • 可能需要等待回复
  • 类似 var task= Task.Run(async () => { HttpResponseMessage response = await client.SendAsync(request); Console.WriteLine("Response status code: {0}", response.状态码); });任务.Wait();
  • @RudreshaParameshappa 请注意我是通过await 完成的。我说的对吗?

标签: c# .net asp.net-core


【解决方案1】:

无需使用ByArrayContent,只需使用StreamContentPostAsync

删除以下代码

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多