2016-08-11 63 views
1

我想檢索Controller Action的結果對象類型。使用反射從MVC中的操作獲取結果對象類型

一般,在我的項目動作的結構是這樣的:

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

現在,我怎樣才能得到使用反射MyControllerResult對象類型?

我寫這個代碼,但我不知道如何檢索對象類型和對象名稱:

var attributes = method.GetCustomAttributes(); // list of attributes 
var resultAttribute = attributes.Where(x => x.ToString().Contains("ServiceControllerResultAttribute")).FirstOrDefault(); 

附:我編寫Contains方法來檢索屬性,因爲裝飾器ServiceControllerResult是可選的。

感謝

回答

1

您可以創建類型的靜態擴展方法(擴展部分可選),並調用它。您仍然需要傳入方法名稱,但可以使用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; } 
} 
+0

對不起伊戈爾但我沒有代碼,我剛通過反射檢索MyMethod的dll。我無法使用您的解決方案。 – elviuz

+0

@elviuz - 它仍然可以使用。查看更新。我刪除了無法更改的方法的主體,併爲正在編寫的代碼添加了一種新方法,您可以在其中使用類型信息來獲取返回類型。 – Igor