c# - 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;
}
解决方案
推荐阅读
- node.js - 如何使用服务帐户访问 GSuite 电子邮件帐户的 GMAIL API
- python - 如何使用 matplotlib 使文本居中?
- php - PEAR 错误 + Open Server 和 Opencart 项目
- javascript - Mousedown 和 mouseup 同时以角度触发
- c# - 客户端和主机应用程序之间通过 Internet 进行 C# 低延迟通信
- java - Java Immutables Polymorphism - 如何使生成的类扩展另一个类?
- c# - 如何在 ASP.NET MVC5 的视图模型中进行字符串“不喜欢”验证?
- python - 使用 Python Cryptography 模块递归加密
- python - 全局变量未在 django 中定义
- sql-server - 如何在 openrowset 和 sql-server 身份验证中将参数传递给存储过程