ASP.NET MVC -- custom Filter

Introduction: filter is the judgment before or after the controller method. This paper mainly introduces the custom filter

1. Filter classification

① Authorize: this filter is used to restrict the behavior of entering the controller

Handle error: this filter is used to formulate a behavior and handle exceptions in a method

2. Conditions that the custom filter must meet

1) implement any one or more filter interfaces

2) inherit FilterAttribue class

3) realize the following

  public class LogExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            //Define log file path
            string filePath = filterContext.HttpContext.Server.MapPath(@"~\log.txt");
            //Write log information
            using (StreamWriter sw = File.AppendText(filePath))
            {
                sw.WriteLine("Time:{0}", DateTime.Now.ToString());
                sw.WriteLine("Controller:{0}", filterContext.RouteData.Values["Controller"]);
                sw.WriteLine("Action method:{0}", filterContext.RouteData.Values["Action"]);
                sw.WriteLine("Exception information:{0}", filterContext.Exception.Message);
            }
        }
    }

3. Use of custom filter

1. Add to a controller method as a feature

      [LogExceptionFilter]//Define a custom filter in the specified action method
        [HttpPost]
        public ActionResult Register(Customer objCustomer, string validateCode)
        {
       
            if (ModelState.IsValid)
            {
                if (String.Compare(TempData["ValidateCode"].ToString(), validateCode, true) != 0)
                {
                    ModelState.AddModelError("ValidateCode", "The verification code is incorrect, please re-enter!");
                    return View("Register");
                }              
                CustomerManager cManager = new CustomerManager();
                if (!cManager.Register(objCustomer))
                {
                    ModelState.AddModelError("doubleUser", "The current user name has been used, please re-enter!");
                    return View("Register");
                }
                else
                {
                    return Content("<script>alert('Registration succeeded, please continue shopping!');window.location='" 
                        + Url.Content("~/") + "'</script>");
                }
            }
            else re

As a learning record, please correct any mistakes.

Posted on Tue, 03 Dec 2019 05:40:07 -0500 by rmelino