1.添加一个特性attribute类
public class CustomerControllerFilterAttribute : Attribute, IActionFilter 、、也可以实现IResourceFilter等 { public void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"This is {typeof(CustomerControllerFilterAttribute)} OnActionExecuting"); } public void OnActionExecuted(ActionExecutedContext context) { Console.WriteLine($"This is {typeof(CustomerControllerFilterAttribute)} OnActionExecuted"); } }
2.在controller上添加特性
[CustomerControllerFilter] public IActionResult Index() { var user = base.HttpContext.Session.GetString("CurrentUser"); if (string.IsNullOrEmpty(user)) { base.HttpContext.Session.SetString("CurrentUser", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } base.ViewBag.User = base.HttpContext.Session.GetString("CurrentUser"); return View(); }