【问题标题】:Is there API to build WebApi route from [RoutePrefix] and [Route] attributes?是否有 API 可以从 [RoutePrefix] 和 [Route] 属性构建 WebApi 路由?
【发布时间】: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


【解决方案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));
}

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 2015-03-29
    • 2015-06-21
    • 2015-10-09
    • 2013-12-05
    • 2016-12-17
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多