When we need to add N controls or actions to the cache and the cached parameters are consistent, we can put the relevant settings on the Web. config, and add the corresponding configuration in the program.
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! -- 3 For more information on how to configure your ASP. NET application, please visit 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 7 <configuration> 8 <appSettings> 9 <add key = "webpages: Version" value = "2.0.0.0"/> 10 <add key = "webpages: enabled "value =" false "/> 11 <add key =" PreserveLoginUrl "value =" true "/> 12 <add key =" ClientValidationEnabled "value =" true "/> 13 <add key = "UnobtrusiveJavaScriptEnabled" value = "true"/> 14 </appSettings> 15 <system. web> 16 <! -- Configure cache --> 17 <caching> 18 <outputCacheSettings> 19 <outputCacheProfiles> 20 <add name = "TestConfigCache" duration = "10"/> 21 </outputCacheProfiles> 22 </ outputCacheSettings> 23 </caching> 24 <! -- Configure cache --> 25
To configure the cache section, you only need to put it under the system. web Section. The following is the method used:
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. web; 5 using System. web. mvc; 6 7 namespace MvcCache. control. controllers 8 {9 public class ConfigController: Controller10 {11 // TestConfigCache is the cache section 12 configured in the configuration file [OutputCache (CacheProfile = "TestConfigCache")] 13 public ActionResult Index () 14 {15 ViewBag. currentTime = System. dateTime. now; 16 return View (); 17} 18 19} 20}
Note: When both Control and Action are applied to the cache, the Action cache is the main factor.
V. Introduction to OutputCache Parameters
The following code defines the OutputCache of mvc4. Because the English version of IDE and framework is used, all annotations are in English. The subsequent explanations mainly explain common attributes. The important content of cache dependency is described separately below.
For details and use of each attribute, see MSDN. Link: https://msdn.microsoft.com/zh-cn/library/system.web.mvc.outputcacheattribute.aspx
1 using System; 2 using System.Web.UI; 3 4 namespace System.Web.Mvc 5 { 6 // Summary: 7 // Represents an attribute that is used to mark an action method whose output 8 // will be cached. 9 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 10 public class OutputCacheAttribute : ActionFilterAttribute, IExceptionFilter 11 { 12 // Summary: 13 // Initializes a new instance of the System.Web.Mvc.OutputCacheAttribute class. 14 public OutputCacheAttribute(); 15 16 // Summary: 17 // Gets or sets the cache profile name. 18 // 19 // Returns: 20 // The cache profile name. 21 public string CacheProfile { get; set; } 22 // 23 // Summary: 24 // Gets or sets the child action cache. 25 // 26 // Returns: 27 // The child action cache. 28 public static System.Runtime.Caching.ObjectCache ChildActionCache { get; set; } 29 // 30 // Summary: 31 // Gets or sets the cache duration, in seconds. 32 // 33 // Returns: 34 // The cache duration. 35 public int Duration { get; set; } 36 // 37 // Summary: 38 // Gets or sets the location. 39 // 40 // Returns: 41 // The location. 42 public OutputCacheLocation Location { get; set; } 43 // 44 // Summary: 45 // Gets or sets a value that indicates whether to store the cache. 46 // 47 // Returns: 48 // true if the cache should be stored; otherwise, false. 49 public bool NoStore { get; set; } 50 // 51 // Summary: 52 // Gets or sets the SQL dependency. 53 // 54 // Returns: 55 // The SQL dependency. 56 public string SqlDependency { get; set; } 57 // 58 // Summary: 59 // Gets or sets the vary-by-content encoding. 60 // 61 // Returns: 62 // The vary-by-content encoding. 63 public string VaryByContentEncoding { get; set; } 64 // 65 // Summary: 66 // Gets or sets the vary-by-custom value. 67 // 68 // Returns: 69 // The vary-by-custom value. 70 public string VaryByCustom { get; set; } 71 // 72 // Summary: 73 // Gets or sets the vary-by-header value. 74 // 75 // Returns: 76 // The vary-by-header value. 77 public string VaryByHeader { get; set; } 78 // 79 // Summary: 80 // Gets or sets the vary-by-param value. 81 // 82 // Returns: 83 // The vary-by-param value. 84 public string VaryByParam { get; set; } 85 86 // Summary: 87 // Returns a value that indicates whether a child action cache is active. 88 // 89 // Parameters: 90 // controllerContext: 91 // The controller context. 92 // 93 // Returns: 94 // true if the child action cache is active; otherwise, false. 95 public static bool IsChildActionCacheActive(ControllerContext controllerContext); 96 // 97 // Summary: 98 // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext) 99 // and supports the ASP.NET MVC infrastructure. It is not intended to be used100 // directly from your code.101 //102 // Parameters:103 // filterContext:104 // The filter context.105 public override void OnActionExecuted(ActionExecutedContext filterContext);106 //107 // Summary:108 // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext)109 // and supports the ASP.NET MVC infrastructure. It is not intended to be used110 // directly from your code.111 //112 // Parameters:113 // filterContext:114 // The filter context.115 public override void OnActionExecuting(ActionExecutingContext filterContext);116 //117 // Summary:118 // This method is an implementation of System.Web.Mvc.IExceptionFilter.OnException(System.Web.Mvc.ExceptionContext)119 // and supports the ASP.NET MVC infrastructure. It is not intended to be used120 // directly from your code.121 //122 // Parameters:123 // filterContext:124 // The filter context.125 public void OnException(ExceptionContext filterContext);126 //127 // Summary:128 // This method is an implementation of System.Web.Mvc.IResultFilter.OnResultExecuted(System.Web.Mvc.ResultExecutedContext)129 // and supports the ASP.NET MVC infrastructure. It is not intended to be used130 // directly from your code.131 //132 // Parameters:133 // filterContext:134 // The filter context.135 public override void OnResultExecuted(ResultExecutedContext filterContext);136 //137 // Summary:138 // Called before the action result executes.139 //140 // Parameters:141 // filterContext:142 // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.143 //144 // Exceptions:145 // System.ArgumentNullException:146 // The filterContext parameter is null.147 public override void OnResultExecuting(ResultExecutingContext filterContext);148 }149 }
Common attributes:
1) CacheProfile: cache name of the configuration file used for caching.
2) Duration: the cache time, in seconds. This attribute can be left empty unless your Location is set to None. It is required in other cases.
3) OutputCacheLocation: Enumeration type, cache location. When it is set to None, all caches will become invalid. The default value is Any.
Any: the page is cached on the browser, proxy server, and web server;
Client: cached in the browser;
DownStream: the page is cached in the browser and any proxy server;
Server: the page is cached on the Web Server;
None: the page is not cached;
ServerAndClient: the page is cached on the browser and web server;
4) VaryByParam: A list of multiple output cache strings separated by semicolons. By default, this string corresponds to the parameters passed by the GET method or to the variables passed by the POST method. When multiple parameters are set, the output cache prepares a document version corresponding to each parameter. Possible values include none, *, and any valid query string or POST parameter names.
If you do not want to specify parameters for different cached content, you can set them to none. If you want to specify all cached content parameters, you can set them *.
Vi. cache dependency
SqlDependency: A value used to identify a group of database names and table name pairs that the Operation's output cache depends on. The SqlCacheDependency class monitors specific SQL Server database tables on all supported SQL Server versions (7.0, 2000,200 5). When database tables are changed, the cache items are automatically deleted, add new items to the Cache.
The concept is easy to understand and mainly involves how to apply it. The following is an application instance. Example Description: the database is a local database. The database name is wcfDemo (the database used for writing the wcf tutorial. It is too lazy and used directly). The listening table name is user. The cache time is 3600 seconds, that is, one hour. The database dependency cycle is 500 milliseconds, that is, whether the database changes under the monitoring every 0.5 seconds. If there is any change, the cache is updated immediately.
Step 1: Create a Control. The test code is as follows:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcCache.Control.Controllers 8 { 9 public class SqlDependencyController : Controller10 {11 [OutputCache(CacheProfile = "SqlDependencyCache")]12 public ActionResult Index()13 {14 ViewBag.CurrentTime = System.DateTime.Now;15 return View();16 }17 18 }19 }
Step 2: configure the CacheProfile as SqlDependencyCache section in the configuration file and configure the cache dependency on the database.
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! -- 3 For more information on how to configure your ASP. NET application, please visit 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 7 <configuration> 8 <! -- Database connection string --> 9 <connectionStrings> 10 <add name = "Conn" connectionString = "server = localhost; database = wcfDemo; uid = sa; pwd = 123456; "providerName =" System. data. sqlClient "/> 11 </connectionStrings> 12 <! -- Database connection string --> 13 <appSettings> 14 <add key = "webpages: Version" value = "2.0.0.0"/> 15 <add key = "webpages: enabled "value =" false "/> 16 <add key =" PreserveLoginUrl "value =" true "/> 17 <add key =" ClientValidationEnabled "value =" true "/> 18 <add key = "UnobtrusiveJavaScriptEnabled" value = "true"/> 19 </appSettings> 20 <system. web> 21 <! -- Configure cache --> 22 <caching> 23 <sqlCacheDependency> <! -- Cache database dependency section --> 24 <databases> 25 <add name = "UserCacheDependency" connectionStringName = "Conn" pollTime = "500"/> <! -- Conn: the name of the database connection string, in the cache section, --> 26 </databases> 27 </sqlCacheDependency> 28 <outputcachesetency> 29 <outputCacheProfiles> 30 <add name = "SqlDependencyCache" duration = "3600" sqlDependency = "UserCacheDependency: user "/> <! -- UserCacheDependency: name of the database dependency configuration section. user: name of the table to be monitored in the database --> 31 </outputCacheProfiles> 32 </outputCacheSettings> 33 </caching> 34 <! -- Configure cache --> 35
Note:
1) because it is a cache-dependent database, it must also contain the connectionStrings section.
2) <add name = "UserCacheDependency" connectionStringName = "Conn" pollTime = "500"/>
ConnectionStringName: name of the database connection string
PollTime: The period in milliseconds for monitoring database changes. Check whether the database changes every 500 milliseconds.
3) <add name = "SqlDependencyCache" duration = "3600" sqlDependency = "UserCacheDependency: user"/>
SqlDependency: name of the data dependency section + colon + data table name (lower case ). If this dependency uses multiple tables, separate them with semicolons, as shown in the following figure: UserCacheDependency: user; UserCacheDependency: user1
Step 3: Enable the cache dependency notification function for the database table
Open the vs command line and enter: aspnet_regsql-S localhost-U sa-P 123456-ed-d wcfDemo-et-t user
-S localhost: Database address
-U sa: Database Login Name
-P 123456: Database logon Password
-D wcfDemo: Database Name
-T user: Table Name (lower case)
The table structure is as follows:
Step 4: test the program. The above example only prints the current time. If no cache dependency is added, all the results that should be run within one hour are the current time, the task does not change every time Ctrl + F5 force refresh the browser. After the cache dependency is added, the cache time will be updated as long as any modification is made to the database data. That is, when the data is changed and the browser is refreshed, the time is changing.