2017-11-30 8 views
1

AspNetCore에서 주어진 FilterContext를 통해 경로 템플릿을 얻으려고합니다. 예 : 나는에서 경로 템플릿을 얻을 수 Microsoft.AspNet.WebApi에서 는 {controller}/{action}/{id?}AspNetCore FilterContext에서 RouteTemplate을 얻을 수 있습니까?

: AspNetCore에서 ControllerContext.RouteData.Route as RouteBase

가 : HttpControllerContext.RouteData.Route.RouteTemplate

나는이에서 얻을 수 System.Web.Mvc에서 FilterContext.ActionDescriptor.AttributeRouteInfo.Template

그러나 모든 경로가 속성 경로는 아닙니다. 검사를 바탕으로

속성을 사용할 수없는 경우, 기본 경로 및/또는 매핑 된 노선에서 조립 될 수 있습니다 FilterContext.RouteData.Routers.OfType<Microsoft.AspNetCore.Routing.RouteBase>().First() 하지만 문서화 또는 단순히 더 나은 방법을 찾고 있어요.

답변

0

조립 된 버전이지만 더 나은 답변을 찾고 있습니다.

FilterContext context; 

string routeTemplate = context.ActionDescriptor.AttributeRouteInfo?.Template; 

if (routeTemplate == null) 
{ 
    // manually mapped routes or default routes 
    // todo is there a better way, not 100% sure that this is correct either 
    // https://github.com/aspnet/Routing/blob/1b0258ab8fccff1306e350fd036d05c3110bbc8e/src/Microsoft.AspNetCore.Routing/Template/TemplatePart.cs 
    IEnumerable<string> segments = context.RouteData.Routers.OfType<Microsoft.AspNetCore.Routing.RouteBase>() 
     .FirstOrDefault()?.ParsedTemplate.Segments.Select(s => string.Join(string.Empty, s.Parts 
      .Select(p => p.IsParameter ? $"{{{(p.IsCatchAll ? "*" : string.Empty)}{p.Name}{(p.IsOptional ? "?" : string.Empty)}}}" : p.Text))); 

    if (segments != null) 
    { 
     routeTemplate = string.Join("/", segments); 
    } 
}