net6中 如何获取所有控制器中的接口
时间: 2024-03-18 13:42:36 浏览: 24
在 .NET 6 中,要获取所有控制器中的接口,可以使用以下代码:
```csharp
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
// 获取所有控制器中的接口
var controllerTypes = typeof(Startup).Assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type));
var actionList = new List<string>();
foreach (var controllerType in controllerTypes)
{
var methods = controllerType.GetMethods().Where(method => method.IsPublic && !method.IsDefined(typeof(NonActionAttribute)));
foreach (var method in methods)
{
var attributes = method.GetCustomAttributes(inherit: true);
var httpMethods = attributes.OfType<HttpMethodAttribute>().SelectMany(attr => attr.HttpMethods);
foreach (var httpMethod in httpMethods)
{
var actionName = method.Name;
var controllerName = controllerType.Name.Replace("Controller", string.Empty);
actionList.Add($"{httpMethod} /{controllerName}/{actionName}");
}
}
}
// 打印所有接口
foreach (var action in actionList)
{
Console.WriteLine(action);
}
```
上述代码首先使用反射获取所有继承自 `ControllerBase` 的控制器类型,然后遍历每个控制器的公共方法,查找带有 `HttpMethodAttribute` 属性的方法,并获取其中的 HTTP 方法和方法名,最后将其添加到列表中,最终打印出所有的接口。需要注意的是,此代码仅适用于基于 MVC 或 Web API 的控制器,不适用于 Razor Pages。