Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

asp.net - How do I apply the OutputCache attribute on a method in a vNext project?

What is the correct way of using the following in a vNext application on an async method:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

I see it is part of System.Web.Caching, but the only place I could add that would be in the aspnet50 -> frameworkAssemblies section of my project.json file, which is incorrect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ASP.NET Core 1.1/2.0 Answer

Add the response caching middleware like so:

public void Configure(IApplicationBuilder application)
{
    application
        .UseResponseCaching()
        .UseMvc();
}

This middleware caches content based on the caching HTTP headers you set in your response. You can take a look at the rest of the answer to see how to use ResponseCache.

ASP.NET Core 1.0 Answer

Use the new ResponseCache attribute instead. ResponseCache is not a direct replacement of OutputCache as it only controls client and proxy caching using the Cache-Control HTTP header.

If you want to use server side caching, see this StackOverflow question discussing how to use IMemoryCache or IDistributedCache.

// Add this to your controller action.
[ResponseCache(Duration = 3600)]

Here is an example using the new cache profiles:

// Add this to your controller action.
[ResponseCache(CacheProfile="Cache1Hour")]

// Add this in Startup.cs
services.AddMvc(options =>
{
    options.CacheProfiles.Add(
        new CacheProfile() 
        {
             Name = "Cache1Hour",
             Duration = 3600,
             VaryByHeader = "Accept"
        });
});

Gotchas

The response caching middleware stops working in a variety of situations which you can learn more about in the docs. Two common ones you will probably hit are that it stops working if it sees an Authorization or Set-Cookie HTTP header.

Bonus Comment

In ASP.NET 4.6, we could represent cache profiles in the web.config and change the settings without recompiling the code. For more information about how you can move your cache profiles to the new appsettings.json, rather than hard coding it in Startup.cs see this question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...