使跨应用程序缓存无效的 ASP.NET 最干净的方法

Ale*_*dro 1 c# asp.net asp.net-mvc caching

我有两个 ASP.NET 应用程序在同一台服务器上运行并共享同一个数据库。一个是前端,用 MVC 开发,它缓存数据以避免数据库调用来检索相同的对象。另一个是后端,使用 WebForms 开发,用于管理 CRUD 操作。

当后端操作发生时,我想使前端缓存无效。我不需要一个完善的机制......后端只会偶尔使用,并且可能会使所有缓存的对象无效。

我遇到了一些解决方案,但它们不是很干净的解决方案......例如,在数据库设置表上放置一个标志,使用共享配置文件,从后端应用程序调用前端 Web 服务。每次调用前端页面时都需要应用每个解决方案,因此我需要尽可能减少资源消耗。

我不想使用 memcached 或 AppFabric 或类似的东西,因为我认为它们对于我的基本需求来说太过分了。

非常感谢!

Vse*_*nin 5

您可以执行使缓存无效的操作。您可以向它传递一个秘密令牌来检查请求是否来自您的其他 Web 应用程序以确保安全。

所以它看起来像这样:

public ActionResult Invalidate(string key)
{
    if (key == ConfigurationManager.AppSettings["ApplicationSecurityKey"])
    {
        _cacheService.Invalidate();
        return Content("ok");
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

在两个web.config项目的两个文件中,您都将拥有:

<appSettings>
    <add key="ApplicationSecurityKey" value="SomeVerySecureValue" />
</appsettings>
Run Code Online (Sandbox Code Playgroud)

您可以从其他 Web 应用程序中调用它,如下所示:

WebClient client = new WebClient();               
client.QueryString.Add("key", ConfigurationManager.AppSettings["ApplicationSecurityKey"]);
string response = client.DownloadString(url)
Run Code Online (Sandbox Code Playgroud)