问题描述
我想过滤我的控制器以删除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。