Home > Mobile >  How to Use Action Filter in Winform App Console app OR any Class Method in C#
How to Use Action Filter in Winform App Console app OR any Class Method in C#

Time:10-12

I Want To Log When any method execution started and when that method execution is completed. so In MVC, I can use Action Filter but I Want the same thing to implement in Console App as well as the Winform app, I have checked there is Postsharp like the NuGet package is available but I don't want to use that.

so is there any other way to implement this kind of thing?

CodePudding user response:

First you need to create a class and extend it from ActionFilterAttribute. now it has four methods that are shown below. you can skip or implement any of these methods according to your requirment

OnActionExecuted(ActionExecutedContext) Called after the action method executes.

OnActionExecuting(ActionExecutingContext) Called before the action method executes.

OnResultExecuted(ResultExecutedContext) Called after the action result executes.

OnResultExecuting(ResultExecutingContext) Called before the action result executes.

   public class GenerateLogsAttribute : ActionFilterAttribute
            {
    //excuted after actionmethod returns
                public override void OnResultExecuted(ResultExecutedContext filterContext)
                {
                   //this code will execute when actionmethod has returned
                }
      public override void OnActionExecuting(ResultExecutedContext filterContext)
                {
                   //this code will start running before action methods start execute
                }
            }

Now you have decorate your actionmethod with attribute of you custom actionfilter (exclude Attribute word) here in our case it will be

  [GenerateLogs]
  public IActionResult YourMethod(){//your code}

and in console App you can create three methods

  1. you want to run before your method (BeforeExecute)

  2. you want to run after your method (AfterExecute)

  3. containing call to methods in this order beforeexecute() yourmethod() afterexecute()

     public string AnotherFunction()
     {
     BeforeExecuting(); //code that you want to run before method start
     YourMethod(); // your actual code
     AfterExecuting(); // code that you want to run after methods has 
     returned
     }
    
  • Related