有没有AspNetCore等同于旧的WebApi IHttpControllerTypeResolver? [英] Is there an AspNetCore equivalent of the old WebApi IHttpControllerTypeResolver?

查看:55
本文介绍了有没有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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆