RestSharp ExecuteAsync UI不等待Rest调用完成

时间:2018-11-18 00:25:09

标签: asp.net-web-api .net-core async-await restsharp nancy

我一直在尝试通过调用使用NancyFx编写的API方法GetFile()从我的angular 6应用程序中下载文件。

GetFile()API方法再次使用RestSharp调用Web API方法GetRemoteFile()。

GetFile()方法遵循异步/等待模式。但是我看到在调用GetRemoteFile()的成功回调之前就已经下载了文件。

因此,下载的文件为0字节。

using RestSharp.Extensions.MonoHttp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using Nancy.Json;
using RestSharp.Extensions;
using System.Net;
using Nancy;
using Nancy.Responses;
using RestSharp;

private async Task<Nancy.Response> GetFile(int orderId)
        {
            var request = new RestRequest($"api/GetRemoteFile", Method.POST);            
            string json = SomeBodyData();
            request.AddJsonBody(new RemoteParameter
            {
                OId = documentId,
                Json = json
            });            
            var taskCompletionSource = new TaskCompletionSource<IResponse>();
            client.BaseUrl = new Uri("http://someremoteapi.com/orders/");            
            var res = client.PostAsync(request, (response,handle) =>
            {   
                taskCompletionSource.SetResult(response);
            });

            var data = await taskCompletionSource.Task;
            var stream = new MemoryStream(data.RawBytes);
            stream.Position = 0;
            var file= new StreamResponse(() => stream, "text/csv");
            return file;
        }

1 个答案:

答案 0 :(得分:0)

遵循异步流程并等待ExecuteTaskAsync。这样,您应该能够获得所需的行为。

private async Task<Nancy.Response> GetFile(int orderId) {
    var request = new RestRequest($"api/GetRemoteFile", Method.POST);
    string json = SomeBodyData();
    request.AddJsonBody(new RemoteParameter {
        OId = documentId,
        Json = json
    });        
    client.BaseUrl = new Uri("http://someremoteapi.com/orders/");
    var response = await client.ExecuteTaskAsync(request);

    var stream = new MemoryStream(response.RawBytes);
    stream.Position = 0;
    var file= new StreamResponse(() => stream, "text/csv");
    return file;
}