ASP.NET 核心路由 - 仅映射特定控制器

ASP.NET Core routing - mapping only specific controllers

根据文档,似乎只能逐条添加单个路由,或者在带注释的(属性路由)控制器中添加所有路由

DOCS: Routing to controller actions in ASP.NET Core

是否可以只添加属于单个控制器的所有路由?

使用 UseEndpoints(e => e.MapControllers()) 将添加所有注释的控制器,使用 UseEndpoints(e => e.MapControllerRoute(...)) 似乎只能添加单个 controller/action 路由,而不是给定控制器中注释的所有路由

示例控制器:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class MyApiController
{

  [Route("/")]
  [Route("[action]")]
  [HttpGet]
  public ResponseType Index()
  {
    // ...
  }

  [Route("[action]")]
  public ResponseType GetListing()
  {
    // ...
  }

}

我找到的一个解决方案是构建一个自定义 MVC 功能提供程序并实现一个扩展方法,允许您准确指定要注册的控制器。

 public static class MvcExtensions
 {
    /// <summary>
    /// Finds the appropriate controllers
    /// </summary>
    /// <param name="partManager">The manager for the parts</param>
    /// <param name="controllerTypes">The controller types that are allowed. </param>
    public static void UseSpecificControllers(this ApplicationPartManager partManager, params Type[] controllerTypes)
    {
       partManager.FeatureProviders.Add(new InternalControllerFeatureProvider());
       partManager.ApplicationParts.Clear();
       partManager.ApplicationParts.Add(new SelectedControllersApplicationParts(controllerTypes));
    }
 
    /// <summary>
    /// Only allow selected controllers
    /// </summary>
    /// <param name="mvcCoreBuilder">The builder that configures mvc core</param>
    /// <param name="controllerTypes">The controller types that are allowed. </param>
    public static IMvcCoreBuilder UseSpecificControllers(this IMvcCoreBuilder mvcCoreBuilder, params Type[] controllerTypes) => mvcCoreBuilder.ConfigureApplicationPartManager(partManager => partManager.UseSpecificControllers(controllerTypes));
 
    /// <summary>
    /// Only instantiates selected controllers, not all of them. Prevents application scanning for controllers. 
    /// </summary>
    private class SelectedControllersApplicationParts : ApplicationPart, IApplicationPartTypeProvider
    {
       public SelectedControllersApplicationParts()
       {
          Name = "Only allow selected controllers";
       }

       public SelectedControllersApplicationParts(Type[] types)
       {
          Types = types.Select(x => x.GetTypeInfo()).ToArray();
       }
 
       public override string Name { get; }
 
       public IEnumerable<TypeInfo> Types { get; }
    }
 
    /// <summary>
    /// Ensure that internal controllers are also allowed. The default ControllerFeatureProvider hides internal controllers, but this one allows it. 
    /// </summary>
    private class InternalControllerFeatureProvider : ControllerFeatureProvider
    {
       private const string ControllerTypeNameSuffix = "Controller";
 
       /// <summary>
       /// Determines if a given <paramref name="typeInfo"/> is a controller. The default ControllerFeatureProvider hides internal controllers, but this one allows it. 
       /// </summary>
       /// <param name="typeInfo">The <see cref="TypeInfo"/> candidate.</param>
       /// <returns><code>true</code> if the type is a controller; otherwise <code>false</code>.</returns>
       protected override bool IsController(TypeInfo typeInfo)
       {
          if (!typeInfo.IsClass)
          {
             return false;
          }
 
          if (typeInfo.IsAbstract)
          {
             return false;
          }
 
          if (typeInfo.ContainsGenericParameters)
          {
             return false;
          }
 
          if (typeInfo.IsDefined(typeof(Microsoft.AspNetCore.Mvc.NonControllerAttribute)))
          {
             return false;
          }
 
          if (!typeInfo.Name.EndsWith(ControllerTypeNameSuffix, StringComparison.OrdinalIgnoreCase) &&
                     !typeInfo.IsDefined(typeof(Microsoft.AspNetCore.Mvc.ControllerAttribute)))
          {
             return false;
          }
 
          return true;
       }
    }
 }

将扩展 class 放在项目的任何地方,然后像这样使用

public void ConfigureServices(IServiceCollection services)
{
  // put this line before services.AddControllers()
  services.AddMvcCore().UseSpecificControllers(typeof(MyApiController), typeof(MyOtherController));
}

来源:https://gist.github.com/damianh/5d69be0e3004024f03b6cc876d7b0bd3

Damian Hickey 提供。