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 的性能和可维护性。