![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we create a LOG filter for Logging purposes in C# ASP.NET WebAPI?
Action filters are used to add extra logic before or after action methods execution. The OnActionExecuting and OnActionExecuted methods are used to add our logic before and after an action method is executed.
Let us create create a LogAttribute that implemets ActionFilterAttribute which logs some information before and after action method execution.
LogAttribute −
Example
using System; using System.Diagnostics; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace DemoWebApplication.Controllers{ public class LogAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext){ Debug.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs"); } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext){ Debug.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs"); } } }
Controller Action −
Example
using System.Web.Http; namespace DemoWebApplication.Controllers{ public class DemoController : ApiController{ [Log] public IHttpActionResult Get(){ //Some logic return Ok(); } } }
Since we have used the Log attribute which has the OnActionExecuting and OnActionExecuted methods implements, the log information will be added to the debug console.
Advertisements