Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีสร้าง LOG Filter สำหรับการ Logging ใน C# ASP.NET WebAPI

Action Filter ใช้สำหรับเพิ่มตรรกะพิเศษก่อนหรือหลังการทำงานของ Action Method โดยใช้เมธอด OnActionExecuting และ OnActionExecuted เพื่อแทรกโค้ดก่อนและหลังการรัน Action Method

มาสร้าง LogAttribute ที่สืบทอดมาจาก ActionFilterAttribute เพื่อบันทึกข้อมูลก่อนและหลังการทำงานของ Action Method

ตัวอย่างโค้ด LogAttribute

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

using System.Web.Http;

namespace DemoWebApplication.Controllers
{
    public class DemoController : ApiController
    {
        [Log]
        public IHttpActionResult Get()
        {
            // Business logic here
            return Ok();
        }
    }
}

จากโค้ดด้านบน เนื่องจากเราใช้ Attribute [Log] ที่มีการ implement OnActionExecuting และ OnActionExecuted ข้อมูล log จะถูกเขียนลงใน Debug Console

วิธีสร้าง LOG Filter สำหรับการ Logging ใน C# ASP.NET WebAPI