Introduction
In this article we will learn about the Hangfire - .Net Library to make our background tasks and jobs easier in ASP.NET 5.0. As we all know, its newly launched Framework officially released in November. Here I am sharing the link to install the SDK for .Net 5

Prerequisites
- What is Hangfire and why do I need background tasks.
- Setup and Configure Hangfire
- Secure the Hangfire Dashboard.
- Hangfire Retention Time.
- Persistence with SQL Database.
What is Hangfire and why do we need to use this?
Hangfire is a .Net Library which helps to create background tasks and make jobs easier in .Net applications. It supports all types of tasks like "fire and forget" and "recurring" and continous jobs as well. You can learn more about this here: Hangfire
Why do I need background tasks?
Background tasks are important in cases where you need to perform an operation or to schedule a task for a particular time. With the background task, the process can continue running in the background where the user cannot wait for the step by step process.
Setup and Configure Hangfire
Create and set up project template with .Net 5

In order to configure Hangfire, we need to install hangfire related packages. Below are the 4 packages that help in configuration and setup authentication and to store job-related information in SQL.

In this project, I have used Data insertion to Database using background tasks - Hangfire and the Code first approach.
Models
Employee.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Threading.Tasks;
- namespace Hangfire.Model
- {
- public class Employee
- {
- [Key]
- public int Id { get; set; }
- public string EmployeeName { get; set; }
- public string Designation { get; set; }
- }
- }

EmployeeDbContext.cs
- using Hangfire.Model;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace Hangfire.AppDbContext
- {
- public partial class EmployeeDbContext : DbContext
- {
- public EmployeeDbContext(DbContextOptions options) : base(options)
- {
- }
- public DbSet<Employee> Employees { get; set; }
- }
- }
appsettings.js
- "ConnectionStrings": {
- "myconn": "server=N-20RJPF2CFK06\\SQLEXPRESS; database=Temp;Trusted_Connection=True;"
- },
Configure the connection string and Hangfire and services injection in the startup file.
Startup.cs
- using Hangfire.AppDbContext;
- using Hangfire.Services;
- using HangfireBasicAuthenticationFilter;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace Hangfire
- {
- public class Startup
- {
- private static IEmployeeService employeeService;
- private readonly Job jobscheduler = new Job(employeeService);
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "Hangfire", Version = "v1" });
- });
- #region Configure Connection String
- services.AddDbContext<EmployeeDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
- #endregion
- #region Configure Hangfire
- services.AddHangfire(c => c.UseSqlServerStorage(Configuration.GetConnectionString("myconn")));
- GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("myconn")).WithJobExpirationTimeout(TimeSpan.FromDays(7));
- #endregion
- #region Services Injection
- services.AddTransient<IEmployeeService, EmployeeService>();
- #endregion
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IBackgroundJobClient backgroundJobClient, IRecurringJobManager recurringJobManager)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Hangfire v1"));
- }
- #region Configure Hangfire
- app.UseHangfireServer();
- //Basic Authentication added to access the Hangfire Dashboard
- app.UseHangfireDashboard("/hangfire", new DashboardOptions()
- {
- AppPath = null,
- DashboardTitle = "Hangfire Dashboard",
- Authorization = new[]{
- new HangfireCustomBasicAuthenticationFilter{
- User = Configuration.GetSection("HangfireCredentials:UserName").Value,
- Pass = Configuration.GetSection("HangfireCredentials:Password").Value
- }
- },
- //Authorization = new[] { new DashboardNoAuthorizationFilter() },
- //IgnoreAntiforgeryToken = true
- }); ;
- #endregion
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- #region Job Scheduling Tasks
- //recurringJobManager.AddOrUpdate("Insert Employee : Runs Every 1 Min", () => jobscheduler.JobAsync(), "*/1 * * * *");
- #endregion
- }
- }
- }



Pradeep AryanPosted May 9, 2021, 1:26 PM
Good Article
Pritesh MaturkarPosted Feb 10, 2021, 8:46 AM
Have you set hangfire in window authentication ?
Pritesh MaturkarPosted Feb 10, 2021, 8:44 AM
It is very Nice Article. Thank you for sharing.
Former memberPosted Jan 22, 2021, 11:39 AM
Thank u for the Article, Nice explanation