elviuz
elviuz

Reputation: 639

Get the result/request object types from a controller in MVC using reflection

I got all the methods that returns an ActionResult from a dll by reflection using this code:

MyAssembly.GetTypes()
                .SelectMany(t => t.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
                .Where(d => d.ReturnType.Name == "ActionResult" && d.IsPublic);

Now, I would like to have the request object and the result object of each controller.

Generally, the structure of a controller in my project is this:

[ServiceControllerResult(typeof(MyControllerResult))]
public ActionResult MyController(MyControllerRequest request)
{
    var response = new ServiceResponse<MyControllerResult>();
    // do something
    return ServiceResult(response);
}

Now, how I can get the MyControllerResult and MyControllerRequest objects from a dll (or from a directory where are stored my referenced ddl) ?

Thanks

Upvotes: 0

Views: 1288

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37996

You can check method parameters to identify request type and investigate method attributes in order to get result type. Assuming ServiceControllerResult attribute has Type property:

foreach (var method in methods)
{
    var parameters = method.GetParameters();
    if (parameters.Length != 1)
    {
        //decide what to do here
        throw new Exception("More than one parameter found");
    }

    var requestType = parameters[0].ParameterType;

    var serviceControllerResultAttribute = method.GetCustomAttribute<ServiceControllerResultAttribute>();
    if (serviceControllerResultAttribute == null)
    {
        //decide what to do here
        throw new Exception("ServiceControllerResultAttribute was not found");
    }

    var resultType = serviceControllerResultAttribute.Type;
}

Upvotes: 2

Related Questions