安裝Hangfire
新建ASP.NET Core空 項目,.Net Core版本3.1
往*.csproj添加包引用,添加新的PackageReference標記。如下所示。請注意,下面代碼段中的版本可能已經過時,如有需要,請使用nuget獲取最新版本。
<ItemGroup>
<PackageReference Include="Hangfire.Core" Version="1.7.28" />
<PackageReference Include="Hangfire.SqlServer" Version="1.7.28" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.7.28" />
</ItemGroup>
創建數據庫
從上面的代碼片段中可以看到,在本文中,我們將使用SQL Server作為作業存儲。在配置Hangfire之前,您需要為它創建一個數據庫,或者使用現有的數據庫。下面的配置字符串指向本地計算機上SQLEXPRESS實例中的HangfireTest數據庫。
您可以使用SQLServerManagementStudio或任何其他方式執行以下SQL命令。如果您使用的是其他數據庫名稱或實例,請確保在接下來的步驟中配置Hangfire時更改了連接字符串。
CREATE DATABASE [HangfireTest]
GO
配置Settings
下面將定義HangfireConnection連接來進行表遷移,同時AspNetCore與Hangfire進行了日志記錄集成。Hangfire的日志信息有時非常重要,有助于診斷不同的問題。信息級別允許查看Hangfire的工作情況,警告和更高的日志級別有助于調查問題,建議調整日志級別
{
"ConnectionStrings": {
"HangfireConnection": "Server=.\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Hangfire": "Information"
}
}
}
更新應用程序設置后,打開Startup.cs文件。startup類是.NET CORE應用程序的配置。首先,我們需要導入Hangfire名稱空間,由于建的是空項目,所以還需要導入Configuration.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Hangfire;
using Hangfire.SqlServer;
注冊服務
使用asp.netcore內置DI注入Hangfire服務
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add Hangfire services.
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(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
services.AddHangfireServer();
}
添加Hangfire面板
如果只是作為后臺作業,也可不使用面板功能,按需添加
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapHangfireDashboard();
});
BackgroundJob.Enqueue(() => Console.WriteLine("測試"));
}
運行程序
生成數據表
訪問
http://localhost:5000/hangfire
添加Hangfire面板授權
新建MyAuthorizationFilter.cs
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
string header = httpContext.Request.Headers["Authorization"];//獲取授權
if(header == null)
return AuthenicateLogin();
//解析授權
var authHeader = AuthenticationHeaderValue.Parse(header);
var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
var username = credentials[0];
var password = credentials[1];
//驗證登錄
if (username == "admin" && password =="123456")
return true;
else
return AuthenicateLogin();
//跳轉簡單登錄界面
bool AuthenicateLogin()
{
httpContext.Response.StatusCode = 401;
httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm="Hangfire Dashboard"");
context.Response.WriteAsync("Authenticatoin is required.");
return false;
}
}
}
Hangfire面板修改
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHangfireDashboard(new DashboardOptions
{
Authorization = new[] { new MyAuthorizationFilter() }
});
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
BackgroundJob.Enqueue(() => Console.WriteLine("測試"));
}
運行程序