【问题标题】:How to restrict allowed methods in Hangfire Server如何限制 Hangfire Server 中允许的方法
【发布时间】:2019-04-15 21:39:19
【问题描述】:

我想将 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


    【解决方案1】:

    根据我提交的 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 贡献者 burnice2866 于 14 天前发表评论

    您应该也可以在 OnPerforming 中设置 Canceled,如此处所述

    Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs
    
    Line 147 in 23d81f5
    
     if (preContext.Canceled)
     {
             return new PerformedContext(
                 preContext, null, true, null);
     }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多