2019年7月17日 星期三

[ASP.Net Core] Hybrid Filter


 ASP.NET Core   Filter  



Introduction


ASP.NET Core supports the Filter types:


And the lifecycle of them is as following (Diagram from Microsoft Docs)


Sometimes we would like to use the already-updated data from some of them.
Here is an example for logging the payload of request and the final HttpStatusCode of response.


Related articles





Environment


.NET Core 2.2.104



Implement


Hybrid filter by implement IActionFilter and IResultFilter

public class HybridFilter: IActionFilter, IResultFilter
{
        private readonly ILogger<LogFilter> _logger = null;
        private ICollection<object> payloads = null;

        public HybridFilter(ILogger<LogFilter> logger)
        {
            this._logger = logger;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            this.payloads = context.ActionArguments == null ? null : context.ActionArguments.Values;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {
            var user = (User)this.payloads.FirstOrDefault();
            int httpStatusCode = context.HttpContext.Response.StatusCode;

            string msg = $"({httpStatusCode.ToString()}) {user.Name} signed in";
            this._logger.LogInformation(msg);
        }

}


Result:




Source code




Reference





沒有留言:

張貼留言