【发布时间】:2016-01-19 06:44:10
【问题描述】:
我有一个 WebApi 应用程序,其中包含一组带有 [RoutePrefix] 和 [Route] 属性标记的控制器和方法。我想通过反射收集所有此类方法,并通过服务器支持的所有 WebApi 调用通知客户端。
我的目标是通知前端登录用户可用的 API 列表,以便前端可以隐藏不允许的方法的控件。
我写了一个简单的代码来完成这项工作。
// GET api/systeminfo/allowedapi
[HttpGet]
[Route("allowedapi")]
[ResponseType(typeof(WebApiCollectionDto))]
public async Task<IHttpActionResult> GetAllowedApi()
{
List<string> apiList = new List<string>();
Type baseControllerType = typeof(ApiController);
IEnumerable<Type> controllerTypes = GetType().Assembly.GetTypes().Where(item => baseControllerType.IsAssignableFrom(item));
foreach (Type controllerType in controllerTypes)
{
RoutePrefixAttribute routePrefixAttribute = controllerType.GetCustomAttribute<RoutePrefixAttribute>();
IEnumerable<MethodInfo> apiMethods = controllerType.GetMethods();
foreach (MethodInfo apiMethod in apiMethods)
{
RouteAttribute routeAttribute = apiMethod.GetCustomAttribute<RouteAttribute>();
if (routeAttribute == null) // not an api method
continue;
string routeTemplate = routeAttribute.Template;
if (routeTemplate.StartsWith("~"))
apiList.Add(routeTemplate.Substring(1));
else
apiList.Add(String.Format("/{0}/{1}", routePrefixAttribute.Prefix, routeTemplate));
}
}
WebApiCollectionDto result = new WebApiCollectionDto(apiList);
return await Task.FromResult(Ok(result));
}
我担心这个实现有点幼稚。为了使这段代码可以生产,我需要在模板的开头和结尾为“/”字符编写额外的处理。那么是否有一个我可以开箱即用的实现?
谢谢。
【问题讨论】:
-
看看 swagger swagger.io 和 webapi 集成 github.com/domaindrivendev/Swashbuckle
-
法律,很好的提示!我已经开始研究 Swashbuckle,看起来他们在内部使用了名为 IApiExplorer 的 Miscrosoft API。所以基本上这就是问题的答案。非常感谢。
标签: c# asp.net-web-api