谢谢大家!实际上,我已经找到了正确的实现方法:
- 定义一个自定义属性:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class DisableBaseOperationsAttribute : Attribute
{
// 空属性类,仅用于标识控制器
}
- 然后实现
IControllerModelConvention
接口,如下所示:
public class ProcessMiningControllerModelConvention : IControllerModelConvention
{
private List<string> baseOperations;
public ProcessMiningControllerModelConvention()
{
baseOperations = new List<string>()
{
"GetAll",
"GetById",
"Insert",
"Update",
"Delete",
};
}
public void Apply(ControllerModel controller)
{
bool disableCrud = controller.Attributes.Any(a => a.GetType() == typeof(DisableBaseOperationsAttribute));
if (disableCrud)
{
var crudActions = controller.Actions.Where(a => baseOperations.Contains(a.ActionName));
foreach (var action in crudActions)
{
action.ApiExplorer.IsVisible = false;
}
}
}
}
- 最后,在配置
AddControllers
时添加控制器模型约定:
builder.Services.AddControllers(s => s.Conventions.Add(new ProcessMiningControllerModelConvention()));
现在您可以在控制器上轻松使用这个属性来禁用基本操作。