如何在 Hangfire 服务器中限制允许的方法

How to restrict allowed methods in Hangfire Server

我想将 Hangfire 服务器处理的作业限制为一组特定的白名单方法或 类。例如,如果客户端 A 排队使用非白名单方法的 Hangfire 作业,则服务器 B 不应执行它。

我考虑过为此目的使用职位筛选器

    class AllowedJobFilter : JobFilterAttribute
    {
        var getMethodInfo(Action a)
        {
            return a.Method;
        }

        void OnPerforming(PerformingContext context) {
            // Only allow jobs which run Console.WriteLine()
            var allowedMethods = new List<MethodInfo>() {
                getMethodInfo(Console.WriteLine),
            };
            if (!allowedMethods.Contains(context.BackgroundJob.Job.Method)
            {
               throw Exception("Method is not allowed");
            }
    }

...
        GlobalConfiguration.Configuration
            .UseFilter(new AllowedJobFilter())

我不确定这种方法是否会按预期工作(因为没有任何内容表明 Hangfire 无法捕获和忽略来自 JobFilterAttribute 的异常),并且这种方法会使作业失败而不是跳过它,这可能不会可取的。有没有更好的方法来限制哪些作业可以 运行 在服务器上?

根据我提交的 Github 问题的回复:

https://github.com/HangfireIO/Hangfire/issues/1403

burningice2866 14 天前评论

您可以在 JobFilter 中实现 OnCreating 方法并将 context.Canceled 设置为 true。正如您在这里看到的那样,使用这种方法在创建过程中可以忽略作业。

Hangfire/src/Hangfire.Core/Client/BackgroundJobFactory.cs

Line 112 in 23d81f5
if (preContext.Canceled)
{
         return new CreatedContext(preContext, null, true, null);
}

@burningice2866 贡献者 burningice2866 评论于 14 天前

您应该也可以按照此处所述在 OnPerforming 中设置已取消

Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs

Line 147 in 23d81f5

 if (preContext.Canceled)
 {
         return new PerformedContext(
             preContext, null, true, null);
 }