2016-08-11 10 views
1

コントローラアクションの結果オブジェクトタイプを取得したいと思います。リフレクションを使用して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(); 

P.S.デコレータServiceControllerResultはオプションであるため、属性を取得するContainsメソッドを記述します。

おかげ

答えて

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

関連する問題