亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

安裝Hangfire

新建ASP.NET Core空 項目,.Net Core版本3.1

.NET Core Hangfire任務計劃

 

往*.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的工作情況,警告和更高的日志級別有助于調查問題,建議調整日志級別

.NET Core Hangfire任務計劃

 

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=.\sqlexpress;Database=HangfireTest;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Hangfire": "Information"
    }
  }
}
.NET Core Hangfire任務計劃

 

更新應用程序設置后,打開Startup.cs文件。startup類是.NET CORE應用程序的配置。首先,我們需要導入Hangfire名稱空間,由于建的是空項目,所以還需要導入Configuration.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Hangfire;
using Hangfire.SqlServer;

注冊服務

使用asp.netcore內置DI注入Hangfire服務

.NET Core 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();
}
.NET Core Hangfire任務計劃

 

添加Hangfire面板

如果只是作為后臺作業,也可不使用面板功能,按需添加

.NET Core 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("測試"));
}
.NET Core Hangfire任務計劃

 

運行程序

生成數據表

.NET Core Hangfire任務計劃

 

訪問
http://localhost:5000/hangfire

.NET Core Hangfire任務計劃

 

添加Hangfire面板授權

新建MyAuthorizationFilter.cs

.NET Core Hangfire任務計劃

 

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;
            }
            
        }
    }
.NET Core Hangfire任務計劃

 

Hangfire面板修改

.NET Core 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("測試"));
   }
.NET Core Hangfire任務計劃

 

運行程序

.NET Core Hangfire任務計劃

 


.NET Core Hangfire任務計劃

 

文檔鏈接:https://docs.hangfire.io/en/latest/getting-started/index.html

分享到:
標簽:NET
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定