Advertisement
Search  
Always will be ready notify the world about expectations as easy as possible: job change page
Oct 20, 2022

HangFire with .NET 6.0

Author:
Ricardo Griffith
Source:
Views:
2976

Schedule and run background jobs using this powerful framework

Disclaimer: the image mentioned in this article is currently marked as preview. Opinions expressed therein are solely my own and do not express the views or opinions of my employer.

Hangfire provides a framework that performs background processing for .NET and .NET Core applications without creating a Windows Service or requiring a separate process. Hangfire is open and free for commercial use (subscriptions allow you to use additional options) and is backed by persistent storage.

The HangFire architecture is simply a client/server model with persistence using Microsoft SQL Server. HangFire Server queries the Storage to perform the required background jobs. The Server component works by using a set of background threads to listen to the Storage for new jobs then performs the required task by de-serializing type, method, and arguments. The Client component creates the background jobs by saving them to the Storage component.

Prerequisites

Installation and Configuration

The instructions below detail a simple HangFire project built using Microsoft’s Visual Studio 2022.

  1. Open Visual Studio 2022.
  2. Create a new project.

3. Select ASP.NET Core Web App.


Click the Next button to move to the next step.

4. Give your Project a name, e.g., MyScheduler.


Click the Next button to move to the next step.

5. Select Windows from the Authentication type and ensure the checkbox is marked: Do not use top level domain statements:


Click the Create button.

6. Add the following NuGet packages:

dotnet add package Hangfire.Core
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer

7. In the Program.cs, add the following right after the following line:

var builder = WebApplication.CreateBuilder(args);

Add the following using statements to the top of this file:

using Hangfire;
using Hangfire.SqlServer;

// Add Hangfire services.
builder.Services.AddHangfire(configuration => configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(builder.Configuration.GetConnectionString(
    "HangfireConnection"), new SqlServerStorageOptions
{
    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
    QueuePollInterval = TimeSpan.Zero,    
    UseRecommendedIsolationLevel = true,
    DisableGlobalLocks = true
}));

// Add the processing server as IHostedService
builder.Services.AddHangfireServer();

For testing purposes, you can place a statement like the following right after the call to app.Run();

BackgroundJob.Enqueue(() => Console.WriteLine(“Hello, world!”));
using (var server = new BackgroundJobServer())
{
    Console.ReadLine();
}

Add the connection string to the appsettings.json file:

"ConnectionStrings": {
    "HangfireConnection": "Server=localhost;Database=HangfireTest;Integrated Security=SSPI;"
},

Adding Dashboard UI

The following code snippet details how you would add the Dashboard UI to use all the Hangfire features immediately. The following steps are fully optional, and you should remove them completely, if your application only creates background jobs.

Authorization configuration required for non-local requests

The default behavior is only local access is permitted to the Hangfire Dashboard. According to the official documentation, Dashboard authorization must be configured to allow remote access.

Right after the app.UseStaticFiles()

add the following line of code:

app.UseStaticFiles();
app.UseHangfireDashboard();

Then, right after the use authorization call, add the following code in bold:

app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapHangfireDashboard();
});

From the official documentation,
“Hangfire Dashboard exposes sensitive information about your background jobs, including method names and serialized arguments as well as gives you an opportunity to manage them by performing different actions — retry, delete, trigger, etc. So, it is important to restrict access to the Dashboard.

To make it secure by default, only local requests are allowed, however you can change this by passing your own implementations of the IDashboardAuthorizationFilter interface, whose Authorize method is used to allow or prohibit a request. The first step is to provide your own implementation.”

public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize (DashboardContext context)
    {
        var httpContext = context.GetHttpContext();

        // IMPORTANT: Allowing authenticated users to see the Dashboard is potentially dangerous!
        return httpContext.User.Identity.IsAuthenticated;
    }
}

The final step will be to add the following to Program.cs:

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new MyAuthorizationFilter() }
});

Now, you can run the application and review the server console window for the Hello World output.

NOTE: When you run the application for the first time, it will create the necessary tables for Hangfire to function in the configured database.

The example project is available on GitHub.

Similar
Feb 1
Author: Sohail Aslam
IntroductionWelcome to the world of C#! Whether you’re a seasoned developer or just starting your programming journey, the power and versatility of C# can elevate your coding experience. In this article, we’ll explore a curated collection of tips and tricks...
Nov 30, 2023
Author: Dev·edium
Keeping your C# applications safe and sound.Keeping app secrets safe is always tricky for developers. We want to work on the main parts of the app without getting distracted by secret-keeping. But, the app’s safety is very important. So, what...
Aug 23, 2022
Author: Luis Rodrigues
Suppose we are building a web api that contains a route to send notification messages to other systems.For security matters, before sending any notification message, we need to provide some credentials to these systems to they accept our messages.However, these...
Mar 25
Author: Henrique Siebert Domareski
Pagination allows you to retrieve a large number of records split into pages, instead of returning all the results at once. This is especially useful in scenarios where you need to retrieve a large number of records. In this article,...
Send message
Email
Your name
*Message


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban