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

เราจะสร้างตัวกรอง LOG เพื่อการบันทึกใน C # ASP.NET WebAPI ได้อย่างไร


ตัวกรองการดำเนินการใช้เพื่อเพิ่มตรรกะพิเศษก่อนหรือหลังการดำเนินการตามวิธีการดำเนินการ วิธี OnActionExecuting และ OnActionExecuted ใช้เพื่อเพิ่มตรรกะของเราก่อนและหลังการดำเนินการตามวิธีการ

ให้เราสร้างสร้าง LogAttribute ที่ใช้ ActionFilterAttribute ซึ่งบันทึกข้อมูลบางอย่างก่อนและหลังการดำเนินการตามวิธีการดำเนินการ

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");
      }
   }
}

การทำงานของคอนโทรลเลอร์

ตัวอย่าง

using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [Log]
      public IHttpActionResult Get(){
         //Some logic
         return Ok();
      }
   }
}

เนื่องจากเราใช้แอตทริบิวต์ Log ซึ่งมีวิธีการ OnActionExecuting และ OnActionExecuted ข้อมูลบันทึกจะถูกเพิ่มไปยังคอนโซลการดีบัก

เราจะสร้างตัวกรอง LOG เพื่อการบันทึกใน C # ASP.NET WebAPI ได้อย่างไร