ControllerFeatureProvider不按名称过滤控制器

问题描述

我想过滤我的控制器以删除NET 5预览中“释放”模式下的“测试”控制器。 看起来在filter类中一切正常(对于“ TestingController”返回false),但是我的控制器在RELEASE模式下仍然可用。

我从类库项目中使用此过滤器类:

public class TestingControllerFeatureProvider : ControllerFeatureProvider
{
    public TestingControllerFeatureProvider()
    {
    }

    protected override bool IsController(TypeInfo typeInfo)
    {
        if (typeInfo != null && typeInfo.Name.ToLower().Contains("testing"))
        {
            return false;
        }

        return base.IsController(typeInfo);
    }
}

以及startup.cs中的这段代码:

IMvcCoreBuilder MVC = services.AddMvcCore();

#if RELEASE
            MVC.ConfigureApplicationPartManager(m =>
            {
                m.FeatureProviders.Add(new TestingControllerFeatureProvider());
            });
#endif

我做错了什么?感谢您的帮助!

解决方法

我认为您可以使用MiddleWare进行操作。首先,您可以在appsettings.json中设置UseTesting。 这是一个演示示例:

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },"AllowedHosts": "*","UseTesting": 1
}

Startup.cs:

 app.UseHttpsRedirection();
            if (Int32.Parse(Configuration["UseTesting"]).Equals(1)) {
                app.Use(async (context,next) =>
                {
                    // Do work that doesn't write to the Response.
                    if (context.Request.Path.Value.ToString().Split("/")[1].Contains("Test"))
                    {
                        context.Response.StatusCode = 404;
                        return;
                    }
                    await next.Invoke();
                    // Do logging or other work that doesn't write to the Response.
                });
            }

在发布模式下,可以在appsettings.json中将UseTesting值更改为1。

结果(我在UseTesting = 1和UseTesting = 0时进行测试): enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...