要在ASP.Net Core中条件性地设置响应缓存,您可以使用ResponseCachingMiddleware中间件和ResponseCacheAttribute特性。以下是一个包含代码示例的解决方案:
首先,在Startup.cs文件的ConfigureServices方法中启用响应缓存服务:
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    // other services
}
然后,在Configure方法中添加ResponseCachingMiddleware中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseResponseCaching();
    // other middlewares
}
接下来,在需要进行缓存的控制器或动作方法上添加ResponseCacheAttribute特性,以设置缓存策略:
[ResponseCache(Duration = 60, VaryByHeader = "User-Agent", VaryByQueryKeys = new[] { "id" })]
public IActionResult Index(int id)
{
    // action logic
}
在上面的示例中,Duration属性设置缓存的持续时间(以秒为单位),VaryByHeader属性指定应该根据的请求标头进行缓存,VaryByQueryKeys属性指定应该根据的查询参数进行缓存。
请注意,还可以在中间件中使用更高级的条件逻辑来根据请求的其他属性进行缓存,例如根据用户角色或其他用户信息。这可以通过自定义中间件来实现。
这是一个使用自定义中间件的示例,根据请求的用户角色设置缓存:
public class CustomResponseCachingMiddleware
{
    private readonly RequestDelegate _next;
    public CustomResponseCachingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        // check user role or other conditions
        if (context.User.IsInRole("Admin"))
        {
            context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = TimeSpan.FromMinutes(30)
            };
        }
        await _next(context);
    }
}
public static class CustomResponseCachingExtensions
{
    public static IApplicationBuilder UseCustomResponseCaching(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware();
    }
}
// In Configure method of Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCustomResponseCaching();
    // other middlewares
}
 在上面的示例中,根据用户角色设置了缓存响应的持续时间和可见性。
希望这可以帮助您条件性地设置响应缓存。