在.NET Core中使用Signalr实现进度条
我把所有的源代码都上传到了我的个人Github,有需要的请自取:https://github.com/WeiMing0803/SignalRProgressBar
效果图
直接上菜
创建一个ASP.NET Core应用程序项目
- 在wwwroot中添加Signalr.js
- 在“解决方案资源管理器”>中,右键单击项目,然后选择“添加”“客户端库”。
- 在“添加客户端库”对话框中:
- 为“提供程序”选择“unpkg”
- 对于“库”,请输入 @microsoft/signalr@latest。
- 选择“选择特定文件”,展开“dist/browser”文件夹,然后选择 signalr.js 和 signalr.min.js。
- 将“目标位置”设置为 wwwroot/js/signalr/。
- 选择“安装” 。
- 在Program.cs中注册SignalR
using SignalrProgressBar.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSignalR(); //添加此处
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapHub<ChatHub>("/chatHub");//添加此处
app.Run();
- 在Hubs文件夹下新建ChatHub.cs文件
public class ChatHub : Hub
{
public async Task UpdateProgress(int progress)
{
await Clients.All.SendAsync("ReceiveProgress", progress);
}
}
- 在HomeController.cs中添加StartProgress方法
private readonly IHubContext<ChatHub> _hubContext;
public HomeController(IHubContext<ChatHub> hubContext)
{
this._hubContext = hubContext;
}
[HttpGet]
public async Task<IActionResult> StartProgress()
{
for (int i = 0; i <= 100; i += 1)
{
await _hubContext.Clients.All.SendAsync("ReceiveProgress", i);
await Task.Delay(1000);
}
return Ok();
}
- 添加chat.js文件
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveProgress", function (progress) {
// 在这里更新进度条
document.getElementById("userInput").value = progress;
var progressBar = document.getElementById("progressBar1");
progressBar.style.width = `${progress}%`;
progressBar.innerHTML = `${progress}%`;
console.log(`Progress: ${progress}%`);
});
connection.start()
.then(function () {
console.log("SignalR connected.");
})
.catch(function (err) {
console.error(err.toString());
});
// 启动进度更新
document.getElementById("sendButton").addEventListener("click", function (event) {
document.getElementById("sendButton").disabled = true;
const showProgressBar = document.getElementById("showProgressBar");
showProgressBar.style.display = "block";
fetch("/Home/StartProgress")
.then(function (response) {
if (response.ok) {
document.getElementById("sendButton").disabled = false;
showProgressBar.style.display = "none";
console.log("Progress started.");
} else {
console.error("Failed to start progress.");
}
})
.catch(function (err) {
console.error(err.toString());
});
event.preventDefault();
})
- 最后在Index.cshtml添加HTML页面
<div class="text-center">
<div id="showProgressBar" style="display:none">
<div class="progress" role="progressbar" aria-label="Example with label" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">
<div id="progressBar1" class="progress-bar" style="width: 0%">0%</div>
</div>
</div>
<div class="row p-1">
<div class="col-6 text-end">
<input type="button" id="sendButton" value="开始" />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<hr />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<input type="button" id="userInput" value="1" />
</div>
</div>
</div>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>