ASP.NET WebAPI - How to Scan Registered Actions

I have several methods in my WebApi that return an HttpResponseMessage. Since the type of response is unknown, I have to register them in HelpPageConfig using something like

config.SetActualResponseType(typeof(X), "SomeController", "GetX");

I would like to register them with a custom attribute [ActualResponse(typeof(X)]where the controller is declared in order to avoid creating a large registry object that references everything in a bit messy list.

How can I poll the configuration to get a list of registered controllers and actions and their attributes so that I can automatically call SetActualResponseType?

+4
source share
1

mvc web api , ​​. mvc/web api - , , , ( ..). ActualResponse, ? , . , . ​​ Application_Start, .

:

public static class ActionMethodsRegistrator
{
    private static readonly Type ApiControllerType = typeof(IHttpController);

    public static void RegisterActionMethods(YourCustomConfig config)
    {
        // find all api controllers in executing assembly            
        var contollersTypes = Assembly.GetExecutingAssembly().GetTypes()
            .Where(foundType => ApiControllerType.IsAssignableFrom(foundType));

        // you may also search for controllers in all loaded assemblies e.g.
        // var contollersTypes = AppDomain.CurrentDomain.GetAssemblies()
        //    .SelectMany(s => s.GetTypes())
        //    .Where(foundType => ApiControllerType.IsAssignableFrom(foundType));                

        foreach (var contollerType in contollersTypes)
        {
            // you may add more restriction here for optimization, e. g. BindingFlags.DeclaredOnly
            // I took search parameters from mvc/web api sources.
            var allMethods = contollerType.GetMethods(BindingFlags.Instance | BindingFlags.Public);

            foreach (var methodInfo in allMethods)
            {
                var actualResponseAttrubute = methodInfo.GetCustomAttribute<ActualResponseAttribute>();
                if (actualResponseAttrubute != null)
                {                       
                    config.SetActualResponseType(actualResponseAttrubute.Type, contollerType.Name, methodInfo.Name);                        
                }
            }
        }
    }
}

Global.asax:

    protected void Application_Start()
    {
        //....
        YourCustomConfig config = InitializeConfig();
        ActionMethodsRegistrator.RegisterActionMethods(config);
    }
0

All Articles