简体   繁体   English

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

[英]ASP.NET Core routing - mapping only specific controllers

Per documentation it seems like it's only possible to add either single routes, one by one, or add all routes in annotated (attribute routing) controllers根据文档,似乎只能逐一添加单个路由,或在带注释的(属性路由)控制器中添加所有路由

DOCS: Routing to controller actions in ASP.NET Core DOCS:路由到 ASP.NET Core 中的控制器操作

Is it possible to add only all routes belonging to single Controller?是否可以只添加属于单个控制器的所有路由?

Using UseEndpoints(e => e.MapControllers()) will add all controllers that are annotated, using UseEndpoints(e => e.MapControllerRoute(...)) seems to be able to add only single controller/action route, not all routes that are annotated in given controller使用UseEndpoints(e => e.MapControllers())将添加所有被注释的控制器,使用UseEndpoints(e => e.MapControllerRoute(...))似乎只能添加单个控制器/动作路由,而不是全部在给定控制器中注释的路由

Sample controller:示例控制器:

using Microsoft.AspNetCore.Mvc;

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

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

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

}

One solution I found is to build a custom MVC feature provider and implement an extension method that allows you to specify exactly which controllers you want registered.我找到的一个解决方案是构建一个自定义 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;
       }
    }
 }

Put the extensions class wherever in your project, and use like this将扩展类放在项目中的任何位置,并像这样使用

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

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

Courtesy of Damian Hickey .达米安·希基提供

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM