WEB API เป็นตัวเลือกที่ดีกว่าสำหรับ Services ที่เรียบง่าย Lightweight WEB API ใช้ Text Format ใดๆ ได้รวมถึง XML และเร็วกว่า WCF
ข้อหลักของ ASP.NET Web API
- ทำงานตาม HTTP Standards - ใช้ HTTP Verbs มาตรฐาน: GET, POST, PUT, DELETE สำหรับ CRUD Operations ทั้งหมด
- Support Routing สมบูรณ์ - Convention-based และ Attribute Routing
- Response Formats - สร้าง Response เป็น JSON และ XML ผ่าน MediaTypeFormatter
- Flexible Hosting - Host ใน IIS ได้ และ Self-host นอก IIS ได้ (Console App, Windows Service, Docker)
- Model Binding และ Validation - Automatic Binding จาก Request, Data Annotations Validation
- OData Support - Query Options ($filter, $orderby, $top, $skip, $expand)
- Stateless - รองรับ Stateless Data Transfer (เหมาะสำหรับ Scalability)
- URL Patterns และ HTTP Methods - RESTful Design Support
หมายเหตุ: OData (Open Data Protocol) เป็น Open Protocol ที่อนุญาตให้สร้างและ Consume Queryable และ Interoperable RESTful APIs อย่างง่ายและมาตรฐาน
เปรียบเทียบ Web API vs WCF
| Feature | ASP.NET Web API | WCF |
|---|---|---|
| Protocol | HTTP/HTTPS เท่านั้น | HTTP, TCP, Named Pipes, MSMQ, Custom |
| Format | JSON, XML, Custom (Content Negotiation) | XML (SOAP), Binary, Custom |
| Performance | เร็วกว่า (Lightweight) | ช้ากว่า (SOAP Overhead) |
| Complexity | Simple, Convention over Config | Complex, Heavy Configuration |
| REST Support | Native, First-class | Limited (WebHttpBinding) |
| Client Reach | Any HTTP Client (Browser, Mobile, JS) | .NET Clients (Best), Others via SOAP |
| Hosting | IIS, Self-host, OWIN, Docker | IIS, WAS, Self-host, Windows Service |
| Testing | Easy (Postman, Browser, curl) | Harder (Need SOAP Client) |
เมื่อไหร่ควรใช้ Web API
- สร้าง RESTful Services สำหรับ Mobile Apps, SPAs (Angular, React, Vue)
- ต้องการ JSON/XML API ที่ Simple และ Fast
- ทีมมี Skill ใน HTTP/REST มากกว่า SOAP/WSDL
- ต้องการ Broad Client Reach (Browsers, Mobile, IoT)
- Microservices Architecture
- Public APIs สำหรับ Third-party Integration
เมื่อไหร่ควรใช้ WCF แทน
- ต้องการ WS-* Standards (WS-Security, WS-ReliableMessaging, WS-Transaction)
- ต้องการ Non-HTTP Transports (TCP, Named Pipes, MSMQ)
- Legacy Systems ที่ใช้ SOAP อยู่แล้ว
- Complex Enterprise Integration Patterns
- Duplex Communication (Callbacks)
Web API ในยุค Modern (.NET Core / .NET 5+)
ASP.NET Core รวม MVC และ Web API เข้าด้วยกันเป็น Framework เดียว:
ControllerBaseสำหรับ API Controllers[ApiController]Attribute ให้ Auto Validation, Binding Source Inference- Built-in Dependency Injection
- Endpoint Routing
- OpenAPI/Swagger Generation Built-in
- Minimal APIs (C# 10+, .NET 6+) สำหรับ Ultra-lightweight APIs
// Minimal API (.NET 6+)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/api/students", () => Students.GetAll());
app.MapGet("/api/students/{id}", (int id) => Students.GetById(id));
app.MapPost("/api/students", (Student s) => Students.Add(s));
app.Run();