首页 > 解决方案 > 如何限制 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 的异常),并且这种方法会使工作失败而不是跳过它,这可能是不可取的。有没有更好的方法来限制哪些作业可以在服务器上运行?

标签: hangfire

解决方案


根据我提交的关于 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 中设置 Canceled ,如此处所述

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

Line 147 in 23d81f5

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


推荐阅读