如何打开 nancy 模块的身份验证作为默认行为

How to turn on authentication for nancy modules as default behavior

可以通过在模块的构造函数中调用 RequiresAuthentication 来为 nancy 模块启用身份验证:

public class CustomModule : NancyModule
{
    public ConfigurationModule()
    {
        this.RequiresAuthentication();

        // ... specify module
    }
}

是否可以默认启用身份验证并添加对禁用它的支持?

我知道可以子类化 NancyModule 并改为使用子类,但这不是我想要的方式。我想加载未引用我的自定义程序集之一的模块。

不幸的是,我没有找到不引用自定义程序集的解决方案。

最后,我想出了以下解决方案:

public abstract class CustomNancyModule : NancyModule
{
    protected CustomNancyModule(bool requiresAuthentication = true, string modulePath = null)
        : base(modulePath ?? string.Empty)
    {
        if (requiresAuthentication)
        {
            this.RequiresAuthentication();
        }
    }
}

和相应的引导程序实现,确保所有模块都派生自 CustomNancyModule:

public class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override IEnumerable<ModuleRegistration> Modules
    {
        get
        {
            var modules = base.Modules;
            var customModuleType = typeof(CustomNancyModule);

            foreach (var module in base.Modules)
            {
                if (!module.ModuleType.IsSubclassOf(customModuleType))
                    throw new InvalidOperationException(
                        $"Module '{module.ModuleType}' is not a sub class of '{customModuleType}'. It is not allowed to derive directly from NancyModule. Please use '{customModuleType}' as base class for your module.");
            }
            return modules;
        }
    }
}