You can provide real-time updates to clients during the file download process with SignalR.Use Hangfire background job. This powerful combination allows for seamless and efficient file downloads in your .NET Core application
· How to use signalr in asp net core?
· Scenario:
· 1- Create .Net Project
· 2- Install Below Packages
· 3- Create New Class Inherit Hub
· 4- Create New Class Inherit IUserProvider
· 5- Add Services Program.cs
· 6- Start SignalR Connection
· 7- Create Login Page to Authenticate User
· 8- Create Fake Download Page
· 9- Show Notification Message
· SignalR File Download Github Source Code
How to use signalr in asp net core?
To use SignalR in ASP.NET Core, you need to install the SignalR package, create a SignalR hub class, configure SignalR in the Startup class, define hub methods for communication, and connect to the SignalR hub from the client-side code. This allows for real-time communication between the server and clients in your ASP.NET Core application.
Scenario:
When users initiate a file download process, they will be able to continue their tasks on the another screen without waiting. Using Hangfire’s background job feature, the file download request will be received, and a connection will be established using SignalR to ensure that the download process starts at a later time.
Lets start.
1- Create .Net Project
Create a .net Web App Razor Page .
2- Install Below Packages
Hangfire:
dotnet add package Hangfire --version 1.8.14
SignalR:
dotnet add package Microsoft.AspNet.SignalR.Core --version 2.4.3
Microsoft.EntityFrameworkCore.Design:
dotnet add package Microsoft.EntityFrameworkCore.Design --version 9.0.0-rc.1.24451.1
Microsoft.EntityFrameworkCore.SqlServer:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 9.0.0-rc.1.24451.1
3- Create New Class Inherit Hub
public class FileDownloadHub : Hub
{
public async Task NotifyDownloadReady(string userId, string fileUrl)
{
await Clients.User(userId).SendAsync("DownloadReady", fileUrl);
}
}
We created a class inherit from Hub. We are sending object to specific user like above using signalr c#.
4- Create New Class Inherit IUserProvider
public class EmailBasedUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
// We are taking user email claim
return connection.User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
}
}
We created this class to take specific userid for signalr connection.
Note: User should be authenticated for it.
5- Add Services Program.cs
We need to add services in program.cs file.
//to authenticate user
#region Authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login";
});
#endregion
//register hangfire service
builder.Services.AddHangfire(x => x.UseSqlServerStorage(builder.Configuration.GetConnectionString("LocalConnection")));builder.Services.AddHangfireServer();//register EmailBasedUserProvider service
builder.Services.AddSingleton<IUserIdProvider,
EmailBasedUserIdProvider>();//register net core signalr service
builder.Services.AddSignalR();
SignalR is needed in the provided code to enable real-time communication between the server and clients for the file download process. By mapping the FileDownloadHub to the “/FileDownloadHub” endpoint using endpoints.MapHub<FileDownloadHub>.
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<FileDownloadHub>("/FileDownloadHub");
});
6- Start SignalR Connection
Firstly don’t forget to call signalr script file at the beginning.
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js"></script>
</head>
We should start a signalr connection writing below js codes in our layout page.
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/FileDownloadHub")
.build();
connection.on("DownloadReady", function (fileUrl) {
//the code is triggering automatic file download
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileUrl.split('/').pop();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
// start SignalR connection
connection.start().then(function () {
console.log("SignalR connection started");
}).catch(function (err) {
console.error(err.toString());
});
</script>
7- Create Login Page to Authenticate User
We created a basic login page to set user info for authentication.
@page
@model signalrfiledownloaddotnetcore.Pages.LoginModel
@{
Layout = null;
}
<head>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</head>
<div class="container d-flex justify-content-center align-items-center min-vh-100">
<div class="card p-4" style="width: 400px;">
<h2 class="text-center mb-4">SignalR File Download</h2>
<h3 class="text-center mb-4">Login</h3>
<p>Enter example email and username </p>
<form method="post">
<!-- Email input -->
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" asp-for="Email" class="form-control" id="email" placeholder="Enter your email"
required>
</div>
<!-- Password input -->
<div class="mb-3">
<label for="text" class="form-label">UserName</label>
<input type="text" asp-for="UserName" class="form-control" placeholder="Enter your username" required>
</div>
<!-- Login button -->
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
</div>
</div>
Authenticate user with specific informations like email, name.
public class LoginModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPost()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, Email),
new Claim(ClaimTypes.Name, UserName),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10),
});
return Redirect("/HomePage");
}
[BindProperty]
public string Email { get; set; }
[BindProperty]
public string UserName { get; set; }
}
8- Create Fake Download Page
We’ll create a fake file download page. The user will trigger file download method using this page.
@page
@model signalrfiledownloaddotnetcore.Pages.FileDownloadModel
@{
}
<div class="col-md-12">
<div class="card">
<div class="card-header">
<form method="post">
<button type="submit" class="btn btn-info">Download File</button>
</form>
</div>
</div>
</div>
//User shoul be authenticated here
[Authorize]
public class FileDownloadModel : PageModel
{
private readonly IHubContext<FileDownloadHub> _hubContext;
public FileDownloadModel(IHubContext<FileDownloadHub> hubContext)
{
_hubContext = hubContext;
}
public void OnGet()
{
}
public IActionResult OnPost()
{
var emailClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
BackgroundJob.Enqueue(() => ProcessFile(emailClaim));
TempData["notification"] = "File download process will be start soon";
return Redirect("/HomePage");
}
public async Task ProcessFile(string userId)
{
await Task.Delay(6000);
string fileUrl = "example.png";
await _hubContext.Clients.User(userId).SendAsync("DownloadReady", fileUrl);
}
- Call the IHubContext with our FileDownloadHub class in constructur.
- Take user emailclaim (authenticated user).
- Trigger ProcessFile method with Hangfire BackgroundJob.
The file download process will start 6 seconds later. We are redirecting user to another page.
9- Show Notification Message
Show a message to user file download process will start soon in homepage or another page.
Microsoft asp net signalr package will start downloading process a few second later automaticly.
Users can look another pages without waiting file download process.
End of the process file download process is starting.
That’s all.
Dont forget follow and support me.
SignalR File Download Github Source Code
You can find below github source code.
Learn more SignalR – Hangfire: File Download with .NET Core
