技術ネタ。
CustomAttribute便利ですよね。プログラムは大好きなんだけど一行でも少なく書きたい主義の僕にはひじょーに素敵な機能です。
パラメータでちょっと動きを変えたい!セッションで持つほどじゃないけどちょっとだけ!!
ってことは割とある?と思うので小ネタを。Areas使うときなんかは結構嬉しいと思う。
まずは普通のCustomAttribute
// HogeController.cs [HogeAttributes] public ActionResult Index(string param) { return View(); } // HogeAttributes.cs public override void OnActionExecuting(ActionExecutingContext filterContext) { // いろんな処理 base.OnActionExecuting(filterContext); }
この例でいくとparamの値によっては違うとこにリダイレクトさせたい!とかあると思います。
その例が以下です。
// HogeController.cs [HogeAttributes] public ActionResult Index(string param) { return View(); } // HogeAttributes.cs public override void OnActionExecuting(ActionExecutingContext filterContext) { // Parameters can be acquired with custom attributes. var param = filterContext.ActionParameters["param"]; // いろんな処理 base.OnActionExecuting(filterContext); }
ActionExecutingContextのActionParametersにメソッドの引数のパラメータ名を渡すと取得出来ます。keyvalueで入ってるので引数の名前変えると落ちます。
このやり方が良いかはわからんが、割と便利なのでオススメです。