Preview.OutputCaching 0.0.2-preview

This is a prerelease version of Preview.OutputCaching.
dotnet add package Preview.OutputCaching --version 0.0.2-preview
NuGet\Install-Package Preview.OutputCaching -Version 0.0.2-preview
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Preview.OutputCaching" Version="0.0.2-preview" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Preview.OutputCaching --version 0.0.2-preview
#r "nuget: Preview.OutputCaching, 0.0.2-preview"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Preview.OutputCaching as a Cake Addin
#addin nuget:?package=Preview.OutputCaching&version=0.0.2-preview&prerelease

// Install Preview.OutputCaching as a Cake Tool
#tool nuget:?package=Preview.OutputCaching&version=0.0.2-preview&prerelease

Output Caching for ASP.NET Core 6.0

A copy of .NET 7.0 Output Caching middleware, targeting .NET 6.0.

Warning !!!

This package is not supported and might be removed in the future. It's goal is to provide a way to test the Output Caching features that will ship in ASP.NET Core 7.0 but on .NET 6.0. Any improvement made to the official version will be ported here.

Sample usage - Minimal APIs

Program.cs
using System.Globalization;
using Microsoft.AspNetCore.OutputCaching;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOutputCache(options =>
{
    // Define policies for all requests which are not configured per endpoint or per request
    options.AddBasePolicy(builder => builder.With(c => c.HttpContext.Request.Path.StartsWithSegments("/js")).Expire(TimeSpan.FromDays(1)));
    options.AddBasePolicy(builder => builder.With(c => c.HttpContext.Request.Path.StartsWithSegments("/js")).NoCache());

    options.AddPolicy("NoCache", b => b.NoCache());
});

var app = builder.Build();

app.UseOutputCache();

app.MapGet("/", Gravatar.WriteGravatar);

app.MapGet("/cached", Gravatar.WriteGravatar).CacheOutput();

app.MapGet("/nocache", Gravatar.WriteGravatar).CacheOutput(x => x.NoCache());

app.MapGet("/profile", Gravatar.WriteGravatar).CacheOutput("NoCache");

app.MapGet("/attribute", [OutputCache(PolicyName = "NoCache")] () => Gravatar.WriteGravatar);

// Only available in dotnet 7
//var blog = app.MapGroup("blog").CacheOutput(x => x.Tag("blog"));
//blog.MapGet("/", Gravatar.WriteGravatar);
//blog.MapGet("/post/{id}", Gravatar.WriteGravatar).CacheOutput(x => x.Tag("blog", "byid")); // Calling CacheOutput() here overwrites the group's policy

app.MapPost("/purge/{tag}", async (IOutputCacheStore cache, string tag) =>
{
    // POST such that the endpoint is not cached itself

    await cache.EvictByTagAsync(tag, default);
});

// Cached entries will vary by culture, but any other additional query is ignored and returns the same cached content
app.MapGet("/query", Gravatar.WriteGravatar).CacheOutput(p => p.VaryByQuery("culture"));

app.MapGet("/vary", Gravatar.WriteGravatar).CacheOutput(c => c.VaryByValue((context) => new KeyValuePair<string, string>("time", (DateTime.Now.Second % 2).ToString(CultureInfo.InvariantCulture))));

long requests = 0;

// Locking is enabled by default
app.MapGet("/lock", async (context) =>
{
    await Task.Delay(1000);
    await context.Response.WriteAsync($"<pre>{requests++}</pre>");
}).CacheOutput(p => p.AllowLocking(false).Expire(TimeSpan.FromMilliseconds(1)));

// Etag
app.MapGet("/etag", async (context) =>
{
    // If the client sends an If-None-Match header with the etag value, the server
    // returns 304 if the cache entry is fresh instead of the full response

    var etag = $"\"{Guid.NewGuid():n}\"";
    context.Response.Headers.ETag = etag;

    await Gravatar.WriteGravatar(context);

    var cacheContext = context.Features.Get<IOutputCacheFeature>()?.Context;

}).CacheOutput();

// When the request header If-Modified-Since is provided, return 304 if the cached entry is older
app.MapGet("/ims", Gravatar.WriteGravatar).CacheOutput();

await app.RunAsync();

Sample usage - ASP.NET Core MVC

Enabling output cache for an MVC action:

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddOutputCache();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseOutputCache();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
HomeController.cs
public class HomeController : Controller
{
    [OutputCache(Duration = 5)]
    public IActionResult Index()
    {
        return View();
    }
}

Sample usage - Razor Page Model

Enabling output cache for a Razor Page:

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddOutputCache();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseOutputCache();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.OutputCaching;

namespace WebApplication4.Pages
{
    [OutputCache(Duration = 5)]
    public class IndexModel : PageModel
    {
        public void OnGet()
        {

        }
    }
}
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Preview.OutputCaching:

Package Downloads
Etch.OrchardCore.OutputCache The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

Orchard Core module that provides caching using Output Cache.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.0.2-preview 15,756 8/2/2022
0.0.1-preview 109 8/1/2022