问题
How to find all controllers and actions with its attribute in dotnet core? In .NET Framework I used this code:
public static List<string> GetControllerNames()
{
List<string> controllerNames = new List<string>();
GetSubClasses<Controller>().ForEach(type => controllerNames.Add(type.Name.Replace("Controller", "")));
return controllerNames;
}
public static List<string> ActionNames(string controllerName)
{
var types =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(IController).IsAssignableFrom(t) &&
string.Equals(controllerName + "Controller", t.Name, StringComparison.OrdinalIgnoreCase)
select t;
var controllerType = types.FirstOrDefault();
if (controllerType == null)
{
return Enumerable.Empty<string>().ToList();
}
return new ReflectedControllerDescriptor(controllerType)
.GetCanonicalActions().Select(x => x.ActionName).ToList();
}
but its not working in dotnet core.
回答1:
How about injecting IActionDescriptorCollectionProvider
to your component that needs to know these things? It's in the Microsoft.AspNetCore.Mvc.Infrastructure
namespace.
This component gives you every single action available in the app. Here is an example of the data it provides:
As a bonus, you can also evaluate all of the filters, parameters etc.
As a side note, I suppose you could use reflection to find the types that inherit from ControllerBase
. But did you know you can have controllers that don't inherit from it? And that you can write conventions that override those rules? For this reason, injecting the above component makes it a lot easier. You don't need to worry about it breaking.
来源:https://stackoverflow.com/questions/44455384/how-to-find-all-controller-and-action