首页 > 解决方案 > MVC 提前异步刷新

问题描述

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

我尝试了下面的代码,但它不起作用,因为片段服务无法正确到达上下文。

我的问题是在 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;
}

标签: c#asp.net-mvcasp.net-mvc-5streamchunked

解决方案


推荐阅读