创建该功能看起来很简单,因为您可以从默认值中派生出来ControllerFeatureProvider
并覆盖IsController
只识别您想要的控制器。
public class SingleControllerFeatureProvider : ControllerFeatureProvider {
readonly Type m_type;
public SingleControllerTypeResolver(Type type) => m_type = type;
protected override bool IsController(TypeInfo typeInfo) {
return base.IsController(typeInfo) && typeInfo == m_type.GetTypeInfo();
}
}
下一部分是在启动过程中将默认提供程序替换为您自己的提供程序。
public void ConfigureServices(IServiceCollection services) {
//...
services
.AddMvc()
.ConfigureApplicationPartManager(apm => {
var originals = apm.FeatureProviders.OfType<ControllerFeatureProvider>().ToList();
foreach(var original in originals) {
apm.FeatureProviders.Remove(original);
}
apm.FeatureProviders.Add(new SingleControllerFeatureProvider(typeof(MySpecialController)));
});
//...
}
如果重写默认实现被认为不够明确,那么您可以实现IApplicationFeatureProvider<ControllerFeature>
直接并提供PopulateFeature
你自己。
public class SingleControllerFeatureProvider
: IApplicationFeatureProvider<ControllerFeature> {
readonly Type m_type;
public SingleControllerTypeResolver(Type type) => m_type = type;
public void PopulateFeature(
IEnumerable<ApplicationPart> parts,
ControllerFeature feature) {
if(!feature.Controllers.Contains(m_type)) {
feature.Controllers.Add(m_type);
}
}
}
参考ASP.NET Core 中的应用程序部分:应用程序功能提供程序 https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-2.0#application-feature-providers
参考发现 ASP.NET Core 中的通用控制器 https://stackoverflow.com/questions/36680933/discovering-generic-controllers-in-asp-net-core