ASP.NET Web API 可以通過多種方式進行優化,以提高性能和可擴展性。以下是一些常見的優化策略:
MemoryCache
)或分布式緩存(如 Redis)。RateLimiterMiddleware
)來防止過多的請求壓垮服務器。[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IMemoryCache _cache;
private readonly IUserService _userService;
public UsersController(IMemoryCache cache, IUserService userService)
{
_cache = cache;
_userService = userService;
}
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUserAsync(int id)
{
var userKey = $"user:{id}";
if (_cache.TryGetValue(userKey, out User user))
{
return user;
}
user = await _userService.GetUserByIdAsync(id);
if (user == null)
{
return NotFound();
}
_cache.Set(userKey, user, TimeSpan.FromMinutes(10));
return user;
}
}
通過上述優化策略,可以顯著提高 ASP.NET Web API 的性能和可維護性。