2017-09-14 8 views
1

IAsyncActionFilterを実装するフィルタを作成し、現在のリクエストのコンテキストのActionParametersとそのResultからデータを取得したいと考えています。私はカスタム属性MyLogAttributeを使用してロギングの挙動を指示しています。重要な情報を含むフィールドをログに記録して表示するようオプトインします。ASP.NETのコアAsyncActionFilterでアクションのアーギュメントと結果を記録する

public class AsyncMyLogFilter : IAsyncActionFilter 
{ 
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 
    { 
     var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; 

     if (actionDescriptor != null) 
     { 
      var attribute = actionDescriptor.MethodInfo.GetCustomAttribute<MyLogAttribute>(); 

      if (attribute != null) 
      { 

       await next(); 

       // This is where the magic is supposed to happen: 
       LoggerHelper.Log(context.ActionArguments, context.Result); 
      } 

      return; 
     } 

     await next(); 
    } 
} 

フィルタはnext()デリゲートを提供方法は、そのポイントを過ぎてアクションが完了されるだろうとObjectResultとして検査結果オブジェクトが利用できることを信じるように私を導きました。しかし、フィルタは問題なくActionArgumentsを取得することができますが、残念なことに、このプロパティは役に立たないだけです。

明白な代替、同期IActionFilterは、私がOnActionExecutedステージ上Resultオブジェクトを調べることができますが、この時点でActionArguments辞書が利用できません。

同じ方法の範囲内でActionArgumentsResultの両方にアクセスする方法はありますか?

-S

+0

引数は 'ActionExecutedContext.ActionDescriptor.Parameters'では使用できませんか? –

+0

Parametersコレクションにはパラメータの名前と型が含まれていますが、値は保持されていません。 –

答えて

0

元の形で問題が解決されていないが、私はIActionFilterと回避策を作成することができました:

public class ActivityLogFilter : IActionFilter 
{ 
    public void OnActionExecuting(ActionExecutingContext context) 
    { 
     var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; 

     if (actionDescriptor != null) 
     { 
      var attribute = actionDescriptor.MethodInfo.GetCustomAttribute<MyLogAttribute>(); 

      if (attribute != null) 
      { 
       context.HttpContext.Items["MyLogData"] = GetRelevantLogData(context.ActionArguments); // Apply some custom logic to select relevant log data 
      } 
     } 

     public void OnActionExecuted(ActionExecutedContext context) 
     { 
      var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; 

      if (actionDescriptor != null) 
      { 
       var attribute = actionDescriptor.MethodInfo.GetCustomAttribute<MyLogAttribute>(); 

       if (attribute != null) 
       { 
        var actionParametersData = (MyActionParametersLogData)context.HttpContext.Items["MyLogData"] 

        LoggerHelper.Log(actionParametersData, context.Result); 
       } 
      } 
     } 
    } 
} 

ない正確にロケット科学。 ("私のHttpContext項目が紛失したらどうしたらいいですか?")、それは仕事をするようです。

-S

関連する問題