我正在研究其中一个项目并遇到一个问题。
我需要使用HttpClient
从外部API检索机场列表。所以这部分是用以下代码完成的
public string URL = @"https://raw.githubusercontent.com/jbrooksuk/JSON-Airports/master/airports.json";
public async Task<IEnumerable<Airport>> getAirportData()
{
HttpResponseMessage httpResponse = await httpClient.GetAsync(URL);
var stream = await httpResponse.Content.ReadAsStreamAsync();
var serializer = new DataContractJsonSerializer(typeof(List<Airport>));
}
Airport.cs:
public class Airport
{
public string iso { get; set; }
public string name { get; set; }
}
现在问题是:检索机场列表应该每5分钟发生一次。应使用响应头来指示应用程序是否从JSON提要中获取其数据
响应标题的名称应为'from-feed'。
有人可以帮忙怎么做?
答案 0 :(得分:0)
您可以使用System.Runtime.Caching.MemoryCache
(内存缓存存储)来实现此目的。您可以存储值,然后稍后检索它们。
(注意:您需要通过右键单击引用 - > gt;添加引用 - &gt;程序集并向下滚动列表来添加System.Runtime.Caching
引用。
以下代码假定它位于Controller中,并且文件顶部有using System.Runtime.Caching
public async Task<IEnumerable<Airport>> GetAirportDataAsync()
{
var cacheKey = "airport-data";
var headerName = "from-feed";
// Safe cast to IEnumerable - Get returns null if the item does not exist in the cache
var data = MemoryCache.Default.Get(cacheKey) as IEnumerable<Airport>;
if (data == null)
{
Response.Headers.Add(headerName, "true");
// Utilize your existing logic to get the data from the API
data = await getAirportDataFromApiAsync();
// Only cache for 5 minutes by providing the expiration time as now + 5 minutes
var expiresAt = DateTime.Now.AddMinutes(5);
// Stores the data read from the API into the cache
MemoryCache.Default.Add(new CacheItem(cacheKey, data),
new CacheItemPolicy
{
AbsoluteExpiration = expiresAt
});
return data;
}
else
{
Response.Headers.Add(headerName, "false");
return data;
}
}