23

我在 ASP.NET MVC 中有一个多租户应用程序。将提供服务的应用程序实例仅是主机名的函数(我想类似于 stackexchange 的东西)。

应用程序的每个实例可能有不同的文化设置(甚至是“自动”,以读取浏览器的语言并尝试使用它),并将相应地进行本地化

在这种情况下,我想对我的一些操作进行一些输出缓存。所以,我的问题是:

  1. 如果输出完全取决于主机名(即忽略本地化要求) ,实现多租户 ASP.NET MVC 应用程序的输出缓存的可能性是什么?

  2. 与 (1) 相同,但现在考虑到输出也取决于文化设置

  3. 与 (2) 相同,但考虑到输出可能会因传递给操作的参数而异?

在这种情况下,我考虑所有站点都从一个 IIS 网站运行。

4

2 回答 2

57

我刚刚想出了如何实现这一目标。

只需使用VaryByHeader属性,设置为"host". 这样做有很多可能性。

方法一

使用OutputCacheAttribute传递所有需要的配置元素,包括VaryByHeader

public class HomeController : Controller
{  
    [OutputCache(Duration = 3600, VaryByParam = "none", VaryByHeader = "host")]
    public ActionResult Index() { /* ... */ }
}

方法2。

或者您可以将其设置为 Web.config 上的配置文件:

<?xml version="1.0"?>
<configuration>
  <!-- ... -->
  <system.web>
    <!-- ... -->
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <clear/>
          <add name="Multitenant" 
               enabled="true"
               duration="3600"
               varyByHeader="host"
               varyByParam="none"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>
</configuration>

然后使用它:

public class HomeController : Controller
{  
    [OutputCache(CacheProfile = "Multitenant")]
    public ActionResult Index() { /* ... */ }
}

方法3。

或者你可以继承OutputCacheAttribute并使用它:

public sealed class MultitenantOutputCacheAttribute : OutputCacheAttribute
{
    public MultitenantOutputCacheAttribute()
    {
        VaryByHeader = "host";
        VaryByParam = "none";
        Duration = 3600;
    }
}

然后使用它:

public class HomeController : Controller
{  
    [MultitenantOutputCache]
    public ActionResult Index() { /* ... */ }
}
于 2010-01-06T10:56:51.070 回答
0

如果人们登陆此页面并在 asp.net 2.x 中寻找等价物。该属性将如下所示:

[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Any, VaryByHeader = "host", VaryByQueryKeys = new string[] { "*" })]

您将需要添加中间件。你需要这个 nuget 包和这个代码:

public void ConfigureServices(IServiceCollection services)
{
    //stuff before...

    services.AddResponseCaching();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    //stuff after...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //stuff before...

    app.UseResponseCaching();

    //stuff after...
}

更多细节在这里

于 2018-11-30T17:42:16.803 回答