Is there an AspNetCore equivalent of the old WebApi IHttpControllerTypeResolver?(有没有AspNetCore等同于旧的WebApi IHttpControllerTypeResolver?)
问题描述
在WebApi中,您可以替换内置的IHttpControllerTypeResolver
,其中您可以随心所欲地找到您想要的Api控制器。
在AspNetCore和MVC中,有一堆令人困惑的PartsManager和FeatureManager,其中的某个地方与控制器有关。我所能找到的所有文档和讨论似乎都假定您是一名从事MVC本身工作的开发人员,并且您已经了解了ApplicationPartManager和ControllerFeatureProvider之间的区别,而无需解释任何内容。 在最简单的示例中,我特别想做的是启动AspNetCore2.0Kestrel服务器的一个实例,并让它只解析预配置的硬编码单一控制器。我明确地不想让它做这是正常的发现和所有的事情。
在WebApi中,您刚刚完成了以下操作:
public class SingleControllerTypeResolver : IHttpControllerTypeResolver
{
readonly Type m_type;
public SingleControllerTypeResolver(Type type) => m_type = type;
public ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) => new[] { m_type };
}
// ...
// in the configuration:
config.Services.Replace(typeof(IHttpControllerTypeResolver), new SingleControllerTypeResolver(typeof(MySpecialController)))
然而,我在尝试使用aspnetcore 2获取等效项时遇到了困难
推荐答案
创建该功能似乎很简单,因为您可以从默认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);
}
}
}
参考Application Parts in ASP.NET Core: Application Feature Providers参考Discovering核心中的通用控制器
这篇关于有没有AspNetCore等同于旧的WebApi IHttpControllerTypeResolver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有AspNetCore等同于旧的WebApi IHttpControllerTypeResolver?


- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01