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 ①...

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:", DateTime.Now.ToString()); sw.WriteLine("Controller:", filterContext.RouteData.Values["Controller"]); sw.WriteLine("Action method:", filterContext.RouteData.Values["Action"]); sw.WriteLine("Exception information:", 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.

3 December 2019, 05:40 | Views: 7737

Add new comment

For adding a comment, please log in
or create account

0 comments