Skip to content

When adding attribute ResponseCacheAttribute, it does not take any effect. #58604

@mturczyn

Description

@mturczyn

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I want to add response cacching to my endpoint, just as I could do with controllers:

[HttpGet(Name = "GetWeatherForecast")]
[ResponseCache(Duration = 30, VaryByHeader = "User-Agent")]
public IEnumerable<WeatherForecast> Get()
{
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

This correctly set the headers (Expires, Vary, etc. depending on the definition) on response.

For that we of course need to call AddResponseCaching and UseResponseCaching to register all services and middleware correctly.

Expected Behavior

As I have analyzed source code for Minimal APIs, the common practice to "bring back" behaviour defined by attrbiute, we simply add the attribute to endpoint's Metadata with such code:

public static RouteHandlerBuilder WithResponseCache(
    this RouteHandlerBuilder builder,
    int durationSeconds,
    string varyByHeader)
{
    builder.Add(endpointBuilder =>
    {
        // This does not work !
        endpointBuilder.Metadata.Add(new ResponseCacheAttribute()
        {
            Duration = durationSeconds,
            VaryByHeader = varyByHeader,
        });
        // This works !!
        //endpointBuilder.Metadata.Add(new AuthorizeAttribute());
    });

    return builder;
}

Expected behavior is that above code should work just as if I defined the ResponseCacheAttribute on the controller's method.

Steps To Reproduce

Just use above code and observe that headers are not set (I have used ASP.NET Core with controllers to compare)

Exceptions (if any)

None

.NET Version

.NET 8

Anything else?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✔️ Resolution: AnsweredResolved because the question asked by the original author has been answered.Status: Resolvedarea-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewaresfeature-response-caching

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions