欢迎光临散文网 会员登陆 & 注册

Asp.Net Core Web Api最佳实践

2023-04-23 20:14 作者:zgcdboy  | 我要投稿
  • 控制器使用属性:ApiController

  • 控制器使用属性:Attribute Routing

  • 模型校验:Model Validation

  • Minimize Controller Size

  • Use Filters to Apply Policies:缓存、模型校验、统一异常处理、统一返回结果类型

  • 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


Asp.Net Core Web Api最佳实践的评论 (共 条)

分享到微博请遵守国家法律