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

问题描述 投票:0回答:1

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

DOCS:路由到 ASP.NET Core 中的控制器操作

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

使用

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

控制器示例:

using Microsoft.AspNetCore.Mvc;

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

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

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

}
c# asp.net-core .net-core routes asp.net-core-mvc
1个回答
5
投票

我发现的一个解决方案是构建一个自定义 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;
       }
    }
 }

将扩展类放在项目中的任何位置,然后像这样使用

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

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

达米安·希基提供。

© www.soinside.com 2019 - 2024. All rights reserved.