安裝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包與ASP進行了日誌記錄整合.NET核心應用程式。Hangfire的日誌資訊有時非常重要,有助於診斷不同的問題。資訊級別允許檢視Hangfire的工作情況,警告和更高的日誌級別有助於調查問題,建議調整日誌級別
{ "ConnectionStrings": { "HangfireConnection": "Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;" }, "Logging": { "LogLevel": { "Default": "Warning", "Hangfire": "Information" } } }
更新應用程式設定後,開啟Startup.cs檔案。startup類是ASP的核心。NET核心應用程式的配置。首先,我們需要匯入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("測試")); }
執行程式