Asp.Net Core Web Api最佳實(shí)踐
控制器使用屬性:ApiController
控制器使用屬性:Attribute Routing
模型校驗(yàn):Model Validation
Minimize Controller Size
Use Filters to Apply Policies:緩存、模型校驗(yàn)、統(tǒng)一異常處理、統(tǒng)一返回結(jié)果類型
async / await
Response Caching
Response Compression
Content Negotiation
Default Exception Handler
ActionResult<T>
ControllBase Base Class
Minimize Controller Size
Keep Controllers Small and Easy to Manage
Minimize logic in action methods
Replace duplicate logic with filters
Avoid business logic
Avoid data access logic
Avoid try-catch
Large controllers tend to:
Lack cohesion
Geteven larger over time
Have more total dependencies and coupling
User Filters and Middleware
Repetitive code in actions/endpoints can be refactored into filters
if it doesn't need MVC details, can user middleward instead
Filters/Middleward == Consistent Policy
Model Validation([ApiController])
Exception Middleware and Logging
Analytics
Response Caching
[ResponseCache] adds cache headers
Used by Clients
Used by intermediate proxies
Not stored on the server by default
Abides by RFC 7234 on HTTP Caching
Add Response Caching Middleward
Supports VaryByParam options
Stores responses in server memory
Response Compression
Rely on Server Compression by default
IIS,IIS Express support compression by default
Dot't Commpress Small Responses
Less than 1000 bytes typically not worth it
Respect Clinet Accept-Encoding Header
Send Content-Encoding Header with response
Use caution with compression and HTTPS
Configuring Content Negotiation(按客戶端要求返回類型:xml,json)
Configuring Exception Handlers
Production Error Handler
Development Error Handler
Minimal APl Swagger Integration