0

我必须在asp.net web api方法中实现缓存,因为我正在访问来自第三方数据源的数据并且调用第三方数据源代价很高,数据只会每24小时更新一次。所以有Strathweb。我的帮助下已经实现了缓存这样Webapi中的服务器端缓存和客户端缓存

/// <summary> 
    /// Returns the sorted list of movies 
    /// </summary> 
    /// <returns>Collection of Movies</returns> 
    [CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan =86400)] 
    public IEnumerable<Movie> Get() 
    { 
     return repository.GetMovies().OrderBy(c => c.MovieId); 
    } 

/// <summary> 
/// Returns a movie 
/// </summary> 
/// <param name="movie">movieId</param> 
/// <returns>Movie</returns> 
[CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan = 86400)] 
public Movie Get(int movieId) 
{ 
     var movie = repository.GetMovieById(movieId); 
     if (movie == null) 
     { 
      var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound) 
      { 
       Content = new StringContent(string.Format("No movie with ID = {0}", movieId)), 
       ReasonPhrase = "Movie ID Not Found" 
      }; 
      throw new HttpResponseException(httpResponseMessage); 
     } 
     return movie; 
} 

但在Strathweb,我已经看到两个属性之一是ClientTimeSpan及其他是ServerTimeSpan.I我不知道何时使用ClientTimeSpan以及何时使用ServerTimeSpan。在最简单的术语中,我想了解何时使用服务器端缓存以及何时使用客户端缓存以及两者之间有什么区别。

+0

[类似的问题在SO](http://stackoverflow.com/questions/17287144/how-to-cache-net-web-api-requests- use-w-angularjs-http)可以帮助你。 – 2014-10-08 05:01:18

回答

1

作为定义说

ClientTimeSpan(对应于CacheControl最大生存周期HTTP报头)

ServerTimeSpan(时间多长的响应应该在服务器端进行缓存)

代码示例,以解释。

//Cache for 100s on the server, inform the client that response is valid for 100s 
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)] 
public IEnumerable<string> Get() 
{ 
    return new string[] { "value1", "value2" }; 
} 


//Inform the client that response is valid for 50s. Force client to revalidate. 
[CacheOutput(ClientTimeSpan = 50, MustRevalidate = true)] 
public string Get(int id) 
{ 
    return "value"; 
} 

SOURCE

+0

感谢Arindam帮助我在2天内解决2个问题。 – F11 2014-10-16 04:48:24

+0

你能帮我解决这个问题吗你能帮我解决这个问题吗?http://stackoverflow.com/questions/26398129/caching-search-result-in-web-api – F11 2014-10-16 09:21:56

2

ClientTimeSpan

使用,如果你想允许客户端(通常是浏览器)在本地缓存用户的计算机上的数据的客户端缓存。好处是客户端可能不会在缓存过期之前请求您的API。另一方面,由于存储在客户端,因此无法使该缓存无效。将此缓存用于非动态/不频繁更改的数据。

ServerTimeSpan

您的服务器上存储数据。你可以很容易地使这个缓存无效,但它需要一些资源(内存)