4

由于Web API中不易支持区域(也因为我需要比项目范围的路由规则更大的灵活性),所以我使用我的控制器上的[RoutePrefix]属性将我的网页API控制器到命名空间,如:Web API帮助页面 - 按路由前缀排序控制器

[RoutePrefix["Namespace1/Controller1"] 
public class Controller1 : ApiControllerBase { } 

[RoutePrefix["Namespace1/Controller2"] 
public class Controller2 : ApiControllerBase { } 

[RoutePrefix["Namespace1/Controller3"] 
public class Controller3 : ApiControllerBase { } 

[RoutePrefix["Namespace2/Controller4"] 
public class Controller4 : ApiControllerBase { } 

[RoutePrefix["Namespace2/Controller5"] 
public class Controller5 : ApiControllerBase { } 

[RoutePrefix["Namespace2/Controller6"] 
public class Controller6 : ApiControllerBase { } 

(这些都是在不同的文件和包含在其中的动作,我只是删除,伴随着实际的名称,简单。)

我生成的帮助文档使用Web API帮助页面,可以正常工作。但是,我想通过我的“名称空间”(按路由前缀分组,然后按字母顺序在每个中进行排序)对文档进行分组和排序。

我决定从订购开始,然后在订单工作后找出分组。要获得订货工作,我想改变我的Index.cshtml [在由Web API帮助页面NuGet包创建的HelpPage区]从这个:

@foreach (IGrouping<HttpControllerDescriptor, ApiDescription> group in apiGroups) 
{ 
    @Html.DisplayFor(m => group, "ApiGroup") 
} 

这样:

@foreach (IGrouping<HttpControllerDescriptor, ApiDescription> group 
    in apiGroups.OrderBy(g => g.Key.GetCustomAttributes<RoutePrefixAttribute>().FirstOrDefault().Prefix) 
       .ThenBy(g => g.Key.ControllerName)) 
{ 
    @Html.DisplayFor(m => group, "ApiGroup") 
} 

然而,我得到一个空引用异常:在上面的LINQ表达式中,g.Key.GetCustomAttributes<RoutePrefixAttribute>().FirstOrDefault()对于我所有的控制器都是空的。这对我来说没有任何意义,因为路由本身工作正常(包括前缀)。有什么建议么?

+0

Web API版本? HelpPage Nuget包版本? – mare

+0

从这里版本5.1:https://aspnetwebstack.codeplex.com/(Nuget饲料:https://www.myget.org/F/aspnetwebstacknightly/)。通常我不喜欢使用夜间构建,但在这种情况下,他们有我需要的必要功能(复杂类型参数的文档)。如果有帮助,该版本的源代码在这里:https://aspnetwebstack.codeplex.com/SourceControl/latest – mayabelle

回答

2

最近有同样的问题...你的LINQ表达式有一个小错误。

apiGroups.OrderBy(g => g.Key.GetCustomAttributes<RoutePrefixAttribute>().FirstOrDefault().Prefix) 

应改为:

apiGroups.OrderBy(g => g.Key.ControllerType.GetCustomAttributes<RoutePrefixAttribute>().FirstOrDefault().Prefix) 

这个工作对我来说,反正。

+0

没有为我工作。我得到相同的结果。 :( 不管怎么说,还是要谢谢你! – mayabelle

2

为了详细解释chris的答案,我能够使用下面的代码块来处理它。我使用的Web API 2.2(版本5.1.2)

@foreach (IGrouping<HttpControllerDescriptor, ApiDescription> group in apiGroups 
    .OrderBy(g => g.Key.ControllerType.GetCustomAttributes<System.Web.Http.RoutePrefixAttribute>().FirstOrDefault().Prefix) 
    .ThenBy(g => g.Key.ControllerName)) 
{ 
    @Html.DisplayFor(m => group, "ApiGroup") 
} 

你需要

@using System.Reflection 

添加到文件的顶部,以获得通用GetCustomAttributes扩展方法为范围。