是否有API从[RoutePrefix]和[Route]属性构建WebApi路由?

时间:2016-01-19 06:44:11

标签: c# asp.net-web-api

我有一个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));
}

我担心这个实现有点天真。为了使这个代码生产就绪,我需要为&#39; /&#39;编写额外的处理。模板开头和结尾的字符。那么可能有一个我可以重复使用的实现吗?

感谢。

1 个答案:

答案 0 :(得分:1)

有来自Miscrosoft的API可以完成这项工作。 System.Web.Http.Description.IApiExplorer

ASP.NET Web API: Introducing IApiExplorer/ApiExplorer

以上代码更清晰的实现:

// GET api/systeminfo/allowedapi
[HttpGet]
[Route("allowedapi")]
[ResponseType(typeof (WebApiCollectionDto))]
public async Task<IHttpActionResult> GetAllowedApi()
{
    List<string> apiList = new List<string>();

    IApiExplorer apiExplorer = Configuration.Services.GetApiExplorer();

    foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
        apiList.Add(apiDescription.RelativePath);

    WebApiCollectionDto result = new WebApiCollectionDto(apiList);
    return await Task.FromResult(Ok(result));
}
相关问题