简体   繁体   中英

ASP.NET 4.6 MVC Output Caching with Razor Syntax Issues

I have an ASP.NET 4.6 project that uses MVC controllers that return my views and WebAPI Controllers that return data.

I want to add output caching to my MVC controllers because I've done a few tests and the performance difference on page load is massive.

[OutputCache(CacheProfile = "PageCache")]
public ActionResult Home()
{
     return View("~/Views/Home/Index.cshtml");
}

The only challenge I'm facing is that the razor syntax on the views is also cached. For example if user 1 loads a route, user 2 will get the same route with the username injected from user 1.

Besides getting rid of all the razor syntax in the pages, what are my options? Does anyone have a good solution to this problem?

You can use VaryByCustom or VaryByParam attributes. The following code is the cache based on the parameter 'id'.

    [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
    public ActionResult Details(int id)
    {
        ViewData.Model = _dataContext.Movies.SingleOrDefault(m => m.Id == id);
        return View();
    }

You can create a cache profile also in the web.config file

<caching>
<outputCacheSettings>
    <outputCacheProfiles>
        <add name="Cache1Hour" duration="3600" varyByParam="none"/>
    </outputCacheProfiles>
</outputCacheSettings>
</caching>

For more info check this Link

You should not cache user information on the server, it should be cached on the client.

Please take a look at this document.

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM