跳到主要内容

Web API & REST


One-Line Memory Hooks (IMPORTANT)

  • Web API → "Expose data over HTTP"
  • REST → "Resources + HTTP verbs"
  • ControllerBase → "API, no views"
  • Stateless → "Every request is independent"
  • ActionResult<T> → "Data + status code"

If you remember just these, you're already interview-safe.


What Is ASP.NET Core Web API?

"HTTP endpoints that return data, not HTML"

Key characteristics

  • Stateless

  • JSON by default

  • Consumed by SPA, mobile apps, other services

  • Uses HTTP verbs (GET, POST, PUT, DELETE)

    Interview line

"ASP.NET Core Web API is used to build lightweight, stateless HTTP services that expose data over RESTful endpoints."


RESTful Principles (ONLY what interviewers expect)

🧠 REST = 5 rules (remember SCURP)

LetterMeaning
SStateless
CClient–Server
UUniform Interface
RResource-based URIs
PCacheable

"REST is an architectural style based on stateless communication, resource-based URIs, and standard HTTP methods."


REST Mapping (Very Testable)

Verb = action, URL = noun

HTTP VerbMeaningExample
GETReadGET /api/products
POSTCreatePOST /api/products
PUTUpdatePUT /api/products/1
DELETEDeleteDELETE /api/products/1

❌ Bad: /getProducts ✅ Good: /products


Web API Controllers (Core Rules)

"API controllers return data, not views"

Must-know facts

  • Inherit from ControllerBase
  • Use [ApiController]
  • Use attribute routing
  • Return JSON
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase

"Web API controllers inherit from ControllerBase and focus on returning data responses like JSON."


API Controllers vs MVC Controllers (Classic Interview Question)

API = data | MVC = HTML

FeatureAPI ControllerMVC Controller
Base classControllerBaseController
ReturnsJSON / XMLViews (HTML)
[ApiController]YesNo
Model validationAutomaticManual
Use caseSPA / MobileRazor pages

"API controllers are for RESTful data services, while MVC controllers are for server-rendered HTML."


Model Binding (Simple Rule)

Route → Query → Body

[HttpGet("{id}")]
public IActionResult Get(int id, [FromQuery] string search)
SourceAttribute
Route{id}
Query[FromQuery]
Body[FromBody]

Validation in Web API

"[ApiController] validates for you"

[Required]
[Range(1, 1000)]
public decimal Price { get; set; }
  • Invalid model → automatic 400
  • No ModelState.IsValid needed in APIs

"With ApiController, model validation is automatic and returns 400 on failure."


9️⃣ Return Types (VERY IMPORTANT)

🧠 Decision rule

NeedUse
Only status controlIActionResult
Data + statusActionResult&lt;T&gt;
Async workTask<>
File downloadFileResult

⭐ Best practice

public async Task<ActionResult<Product>> Get(int id)

"ActionResult<T> is preferred because it allows returning both data and HTTP status codes."


Common HTTP Status Codes (Must recall)

CodeMeaning
200OK
201Created
204No Content
400Bad Request
404Not Found
500Server Error

EF Core + Web API (Real-World Flow)

Controller → DbContext → DbSet → Database

private readonly AppDbContext _context;

Key rules:

  • Use async (ToListAsync)
  • Inject DbContext
  • Use migrations
  • Don't block threads

"EF Core integrates with Web API via DbContext and async CRUD operations."


ControllerBase (Why it exists)

"Controller without views"

Provides:

  • Ok()
  • NotFound()
  • BadRequest()
  • CreatedAtAction()
  • NoContent()

"ControllerBase is optimized for APIs and excludes view-related features."


(Gold)

"ASP.NET Core Web API is used to build RESTful, stateless HTTP services that expose resources over standard HTTP verbs. REST focuses on resource-based URIs, stateless communication, and proper HTTP status codes. API controllers inherit from ControllerBase, use ApiController for automatic validation, and typically return ActionResult<T>. EF Core is commonly used for data access with async CRUD operations. API controllers return JSON, while MVC controllers return HTML views."


🧠 Ultra-Short Cheat Sheet

REST = resource + verb
API → ControllerBase
MVC → Controller
Stateless always
ActionResult&lt;T&gt; > IActionResult
EF Core + async