据我所知,[ApiController] 约定没有内置的可扩展性,但您可以使用application model 实现您想要的。
这是一个 IControllerModelConvention 的示例实现,它查找 [ApiController] 属性,您可以填写您的具体实现:
public class ExampleControllerModelConvention : IControllerModelConvention
{
public void Apply(ControllerModel controllerModel)
{
if (controllerModel.Attributes.OfType<ApiControllerAttribute>().Any())
{
// ...
}
}
}
您可以在 Startup.ConfigureServices 或 Program.cs 中为 .NET 6+ 注册此约定:
// Startup.ConfigureServices
services.AddControllers(options =>
{
options.Conventions.Add(new SampleControllerModelConvention());
});
// Program.cs
builder.Services.AddControllers(options =>
{
options.Conventions.Add(new SampleControllerModelConvention());
});
您链接到的ApiBehaviorApplicationModelProvider 类中的IsApiController 方法处理检查的方式略有不同:
private static bool IsApiController(ControllerModel controller)
{
if (controller.Attributes.OfType<IApiBehaviorMetadata>().Any())
{
return true;
}
var controllerAssembly = controller.ControllerType.Assembly;
var assemblyAttributes = controllerAssembly.GetCustomAttributes();
return assemblyAttributes.OfType<IApiBehaviorMetadata>().Any();
}
此实现支持将[ApiController] 属性应用于控制器所在的程序集。如果您还使用视图,则可能不需要此属性,但值得注意的是这种方法的区别。