.NET Web API: 获取给定方法的路由值

.NET Web API: Get Route Value for a given Method

是否可以 return 基于 .NET Core 中给定方法名称的路由?

例如

以下是 HttpGet 请求,可在“apple/all/expanded”

上访问
       [Route("apple/all/expanded")]
       [HttpGet]
       public object GetAllApplesExpanded()
       {

           return apples;

       }

问题是在另一个class或controller中是否可以简单地传入路由(“apple/all/expanded”)的值方法的名称 (GetAllApplesExpanded) 而不是硬编码路由值?

您可以在其他控制器中尝试以下代码。

 Assembly asm = Assembly.GetExecutingAssembly();
        var e = asm.GetTypes()
               .Where(type => typeof(Yourcontroller)
               .IsAssignableFrom(type))
               .SelectMany(type => type.GetMethods()).Where(c => c.Name == "GetAllApplesExpanded").FirstOrDefault()
               .CustomAttributes.Where(c => c.AttributeType.Name == "RouteAttribute").FirstOrDefault()
               .ConstructorArguments.FirstOrDefault().Value;

测试结果: