C# 使用反射从MVC中的操作获取结果对象类型

C# 使用反射从MVC中的操作获取结果对象类型,c#,.net,asp.net-mvc,reflection,C#,.net,Asp.net Mvc,Reflection,我想检索控制器操作的结果对象类型 通常,我的项目中的行动结构如下: [ServiceControllerResult(typeof(MyControllerResult))] public ActionResult MyMethod(MyControllerRequest request) { var response = new ServiceResponse<MyControllerResult>(); // do something return Ser

我想检索控制器操作的结果对象类型

通常,我的项目中的行动结构如下:

[ServiceControllerResult(typeof(MyControllerResult))]
public ActionResult MyMethod(MyControllerRequest request)
{
    var response = new ServiceResponse<MyControllerResult>();
    // do something
    return ServiceResult(response);
}
另外,我编写Contains方法来检索属性,因为decorator
ServiceControllerResult
是可选的


谢谢

您可以在类型上创建一个静态扩展方法(扩展部分可选)并调用它。您仍然需要传入方法名称,但可以使用
nameof
使其成为类型安全的。唯一可能的问题是,如果您有名称冲突(相同)的方法,那么您必须更改实现以传入
MethodInfo
类型,或者选择第一个匹配并应用属性的可用方法

// your existing method
[ServiceControllerResult(typeof(MyControllerResult))]
public ActionResult MyMethod(MyControllerRequest request)
{/*some code here*/}
新增代码:

public void SomeMethodYouWrote()
{
    var fullTypeOfResult = typeof(YourControllerYouMentionAbove).GetServiceControllerDecoratedType("MyMethod");
}

// added helper to do the work for you so the code is reusable
public static class TypeHelper
{
    public static Type GetServiceControllerDecoratedType(this Type classType, string methodName)
    {
        var attribute = classType.GetMethod(methodName).GetCustomAttributes(typeof(ServiceControllerResultAttribute), false).FirstOrDefault() as ServiceControllerResultAttribute;
        return attribute == null ? null : attribute.ResultType;
    }
}
虽然你的问题中暗示了这一点,但我还是添加了这一点,以便编译

public class ServiceControllerResultAttribute : Attribute
{
    public ServiceControllerResultAttribute(Type someType)
    {
        this.ResultType = someType;
    }
    public Type ResultType { get; set; }
}

对不起,Igor,我没有代码,我只有一个通过反射检索的带有MyMethod的dll。我不能使用你的解决方案。@elviuz-它仍然可以使用。请参阅更新。我删除了您不能更改的方法的主体,并为您正在编写的代码添加了一个新方法,您可以使用类型信息获取返回类型。
public class ServiceControllerResultAttribute : Attribute
{
    public ServiceControllerResultAttribute(Type someType)
    {
        this.ResultType = someType;
    }
    public Type ResultType { get; set; }
}