1

Is it possible to list all the action methods along with return types and parameters, of a WebApi application.

I saw a similar question and asnwered as well, but were for MVC (Getting All Controllers and Actions names in C#). But I tried to do some changes to in webapi, but couldnt do it.

Panda1122
  • 101
  • 1
  • 10
  • 1
    you might want to take a look at [swagger](https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-6.0) – JonasH Mar 17 '22 at 14:43
  • What issues are you having? A client and server controller are basically the same. When a request/response is performed the following occurs 1) Client sends request with POST 2) Server receives request with GET 3) Server processes the request 4) Server sends Response with POST 5) Client receives response with GET. – jdweng Mar 17 '22 at 14:48
  • @JonasH : Swagger needs input. I need something to get me, all registered controllers, their action methods and params of a WebAPI application. This get you all registered controllers of a webapi application. Struggling to get action methods list under them. `Assembly.GetCallingAssembly().GetTypes().Where( type => type.IsSubclassOf(typeof(ApiController))).ToList()` – Panda1122 Mar 22 '22 at 05:41

1 Answers1

0

Below code will get you all required information.

var controlleractionlist = asm.GetTypes()
                .Where(type => typeof(ApiController).IsAssignableFrom(type))
                .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
                .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
                .Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, 
                            ReturnType = x.ReturnType.Name, 
                    Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))), 
                    ControllerRouteAttr = ((System.Web.Http.RoutePrefixAttribute)Attribute.GetCustomAttribute(x.DeclaringType, typeof(System.Web.Http.RoutePrefixAttribute)))?.Prefix,
                    MethodRouteAttr = ((System.Web.Http.RouteAttribute)Attribute.GetCustomAttribute(x, typeof(System.Web.Http.RouteAttribute)))?.Template,
                    params1 = String.Join(",", x.GetParameters().Select(a => a.Name)),
                    returnType = String.Join(",", x.GetParameters().Select(a => a.Name.GetType()))
                })
                .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
Panda1122
  • 101
  • 1
  • 10