public class LoggingFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string actionName = filterContext.ActionDescriptor.ActionName; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string message = $"Executing action {actionName} in controller {controllerName}"; MyLogger.Log(message); } }
public class ValidationFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { ModelStateDictionary modelState = filterContext.Controller.ViewData.ModelState; if (!modelState.IsValid) { filterContext.Result = new ViewResult { ViewName = "ValidationError" }; } } }In this example, we have created a custom action filter attribute that checks whether the model state is valid before executing the action method. If the model state is not valid, we set the filterContext.Result property to a ViewResult that displays a validation error message. Package Library: System.Web.Mvc is part of the ASP.NET MVC framework, which is included in the Microsoft.AspNet.Mvc NuGet package.