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

Filter ประเภทใดบ้างใน C# ASP.NET WebAPI

Filter ใช้สำหรับแทรก Logic เพิ่มเติมในระหว่าง Request Pipeline ของ Web API ใช้สำหรับ Cross-cutting Concerns เช่น Logging, Authorization, Caching สามารถ Apply ได้ที่ Action, Controller หรือ Global (WebApiConfig.cs)

ประเภทของ Filters

  • Authentication Filter: ตรวจสอบความถูกต้องของ User (IAuthenticationFilter)
  • Authorization Filter: ตรวจสอบสิทธิ์การเข้าถึง (IAuthorizationFilter) เช่น [Authorize]
  • Action Filter: เพิ่ม Logic ก่อน/หลัง Action Method (OnActionExecuting, OnActionExecuted)
  • Exception Filter: จัดการ Unhandled Exception (IExceptionFilter) ยกเว้น HttpResponseException
  • Override Filter: ปิดการทำงาน Filter อื่นๆ ที่ระดับสูงกว่า สำหรับ Action/Controller เฉพาะ

ระดับการ Apply Filter

  • Controller Level
  • Action Method Level
  • Global Level (WebApiConfig.cs)

ตัวอย่าง Authorization Filter

using System.Web.Http;

namespace DemoWebApplication.Controllers
{
    public class DemoController : ApiController
    {
        [Authorize]
        public IHttpActionResult Get()
        {
            return Ok();
        }
    }
}

หากไม่มี Authorization ที่ถูกต้อง (Bearer Token, API Key, OAuth) จะได้ 401 Unauthorized:

Filter ประเภทใดบ้างใน C# ASP.NET WebAPI