MVC异步更早冲洗

时间:2018-08-15 13:25:31

标签: c# asp.net-mvc asp.net-mvc-5 stream chunked

我想做什么创建一个片段类,它将为每个片段并行调用片段服务。片段服务将请求获取内容,然后将响应写入并刷新流到浏览器。

我尝试了下面的代码,但由于片段服务无法正确到达上下文而无法正常工作。

我的问题是什么是在ASP.NET MVC 5中实现我的目标的最佳方法?


  

这是我的观点

<div>
    @Fragment.Render()
</div>
  

这是我的片段类

public static async Task<ActionResult> Render(string names){

    HttpContext context = HttpContext.Current;
    Task t1 = Task.Run(() => FragmentService.Get("https://raw.githubusercontent.com/corysimmons/colors.json/master/colors.json", context));
    Task t2 = Task.Run(() => FragmentService.Get("https://raw.githubusercontent.com/nlohmann/json/develop/CMakeLists.txt", context));
    Task t3 = Task.Run(() => FragmentService.Get("https://raw.githubusercontent.com/nlohmann/json/develop/meson.build", context));

    await Task.WhenAll(t1, t2, t3);

    return new JsonResult();
}
  

这是我的片段服务

public Task Get(string url, HttpContext context){

    using (HttpClient client = new HttpClient())
    {
        var response = client.GetAsync(url).Result;
        response.EnsureSuccessStatusCode();
        using (var stream = response.Content.ReadAsStreamAsync().Result)
        {
            using (StreamReader streamReader = new StreamReader(stream))
            {
                string line;
                while ((line = streamReader.ReadLine()) != null)
                {
                    context.Response.Write(line);
                    context.Response.Flush();
                }
            }
        }
    }

    return Task.CompletedTask;
}

0 个答案:

没有答案