web-dev-qa-db-ja.com

ASP.NET MVCアプリでカスタムアクションフィルターに変数を渡す方法

MVCアプリにコントローラーがあり、onResultExecutedメソッドを使用して、カスタムActionFilterAttributeを使用して詳細をログに記録しようとしています。

私はこのチュートリアルを読みます自分のアクションフィルターを理解して記述します。問題は、コントローラーからアクションフィルターに変数を渡す方法ですか?

  1. コントローラーの呼び出しに使用される入力変数を取得したいのですが。ユーザー名/ユーザーIDと言います。
  2. (状況によっては)コントローラーメソッドによって例外がスローされた場合、エラーもログに記録します。

コントローラ-

[MyActionFilter]
public class myController : ApiController {
    public string Get(string x, int y) { .. }
    public string somemethod { .. }
}

アクションフィルター-

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void onActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        // HOW DO I ACCESS THE VARIABLES OF THE CONTROLLER HERE
        // I NEED TO LOG THE EXCEPTIONS AND THE PARAMETERS PASSED TO THE CONTROLLER METHOD
    }
}

ここで問題を説明できれば幸いです。ここでいくつかの基本的なオブジェクトを見逃している場合は、申し訳ありませんが、これはまったく初めてです。

23
divyanshm

アプローチ-1

アクションフィルター

public class MyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    }
}

アクションメソッド

[MyActionFilter]
public ActionResult Index()
{
    ViewBag.ControllerVariable = "12";
    return View();
}

enter image description here

スクリーンショットに注目すると、ViewBag情報を確認できます

アプローチ-2

アクションフィルター

public class MyActionFilter : ActionFilterAttribute
{
    //Your Properties in Action Filter
    public string Property1 { get; set; }
    public string Property2 { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
    }
}

アクションメソッド

[MyActionFilter(Property1 = "Value1", Property2 = "Value2")]
public ActionResult Index()
{
    return View();
}
70
Imad Alazani