ASP. net mvc custom filter attributes implement log Functions

Source: Internet
Author: User

BKJIA recommends ASP. net mvc Framework video tutorial to you. We hope this tutorial will help you better understand ASP. net mvc.

Currently, Enterprise-level development projects, especially websites, generally use the log function. Think about most of them, either using the Enterprise Logging Application Block function or writing a component to record system log events, better tracking and understanding of system operation, ASP is now used. net mvc filter attribute to implement the log function!

ASP. net mvc filter is an attribute that can be applied to the controller's later action. when the Controller or action method is called, ASP. net mvc filters are triggered before and after the call. First, let's take a look at the inheritance used when the action in the Control is called. The custom log class:

To achieve the above effect, you can customize a class of LogMessageAttribute, which inherits the IActionFilter and IResultFilter interfaces and can also inherit and override the class FilterAttribute.

IActionFilter interface is defined:

 
 
  1. public interface IActionFilter  
  2. {  
  3.     // Methods  
  4.     void OnActionExecuted(ActionExecutedContext filterContext);  
  5.     void OnActionExecuting(ActionExecutingContext filterContext);  

OnActionExecuting: Run before calling the action method in the Controller.

OnActionExecuted: it is run after the action method in the Controller is called, but before the OnResultExecuting method of the IResultFilter interface is executed

IResultFilter interface is defined:

 
 
  1. public interface IResultFilter  
  2. {  
  3.     // Methods  
  4.     void OnResultExecuted(ResultExecutedContext filterContext);  
  5.     void OnResultExecuting(ResultExecutingContext filterContext);  

OnResultExecuting: The action method in the Controller is called and executed before play.
OnResultExecuted: The action method in the Controller is called and processed.

Next is the main scene: LogMessageAttribute custom class

 
 
  1. [AttributeUsage (AttributeTargets. Class | AttributeTargets. Method, Inherited = true, AllowMultiple = true)]
  2. Public class LogMessageAttribute: FilterAttribute, IActionFilter, IResultFilter
  3. {
  4. /// <Summary>
  5. /// <Param name = "LogName"> log file path </para>
  6. /// </Summary>
  7. Public string LogName {get; set ;}
  8.  
  9.  
  10. /// <Summary>
  11. /// Record the time, system version, current thread ID, and other records
  12. /// </Summary>
  13. /// <Param name = "controller"> </param>
  14. /// <Param name = "action"> </param>
  15. /// <Param name = "message"> </param>
  16. Public void LogMessage (string controller, string action, string message)
  17. {
  18. If (! String. IsNullOrEmpty (LogName ))
  19. {
  20.  
  21. TextWriter writer = new StreamWriter (LogName, true );
  22. Writer. writeLine #################");
  23. Writer. WriteLine ("Time: [{0}]", DateTime. Now. ToString ("yyyy-MM-dd-hh: mm: ss "));
  24. Writer. WriteLine ("Controller: {0}", controller );
  25. Writer. WriteLine ("Action: {0}", action );
  26. Writer. WriteLine ("Message: {0}", message );
  27. Writer. WriteLine ("Operating System version is: {0}", System. Environment. OSVersion. Version. ToString ());
  28. Writer. WriteLine ("Current Thread ID is: {0}", AppDomain. GetCurrentThreadId ());
  29. Writer. WriteLine ("############### Over ###############");
  30. Writer. Close ();
  31.  
  32. }
  33. }
  34. Public void OnActionExecuting (ActionExecutingContext filterContext)
  35. {
  36. LogMessage (filterContext. RouteData. Values ["controller"]. ToString (),
  37. FilterContext. RouteData. Values ["action"]. ToString (),
  38. "Action exeuting ...");
  39. }
  40. Public void OnActionExecuted (ActionExecutedContext filterContext)
  41. {
  42. LogMessage (filterContext. RouteData. Values ["controller"]. ToString (),
  43. FilterContext. RouteData. Values ["action"]. ToString (),
  44. "Action executed .");
  45. }
  46. Public void OnResultExecuting (ResultExecutingContext filterContext)
  47. {
  48. LogMessage (filterContext. RouteData. Values ["controller"]. ToString (),
  49. FilterContext. RouteData. Values ["action"]. ToString (),
  50. "Result executing ...");
  51. }
  52. Public void OnResultExecuted (ResultExecutedContext filterContext)
  53. {
  54. LogMessage (filterContext. RouteData. Values ["controller"]. ToString (),
  55. FilterContext. RouteData. Values ["action"]. ToString (),
  56. "Result executed ");
  57. }
  58. }

Customize the LogMessageAttribute class and apply it to the attributes of Controller or action. When the Controller is executing or a View is displayed and an HTTP request data is sent, some logs are recorded in the log file.

Apply custom attributes to the project Controller.

 
 
  1. [Logging(LogName = @"D:\Project\Project\MVCProject\sky.ExtendMVCFramework\sky.ExtendMVCFramework\Log.log")]  
  2.      public ActionResult DesplayEmployee()  
  3.      {  
  4.          ViewData["Message"] = "Our employees welcome you to our site!";  
  5.          List<Employee> employees = new List<Employee>  
  6.           {  
  7.               new Employee {  
  8.                   FirstName="sky",  
  9.                   LastName="yang",  
  10.                   Email = "weflytotti@163.com",  
  11.                   Department ="Development" 
  12.               },  
  13.               new Employee {  
  14.                   FirstName="sky",  
  15.                   LastName="yang",  
  16.                   Email = "weflytotti@163.com",  
  17.                   Department ="Development" 
  18.               }  
  19.           };  
  20.          return View(employees);  
  21.      }  

Run the program, as you can see at the beginning of the article!

Conclusion: To customize ASP. net mvc filter attributes, you only need to inherit IActionFilter and IResultFilter to implement the desired functions.

Original article title: ASP. net mvc custom filter attribute for Enterprise log function

Link: http://www.cnblogs.com/skyyang/archive/2010/04/30/1724580.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.