Просмотр исходного кода

[Blazor] Disable caching the response whenever we render a server-side blazor component (#29882)

Fixes #22459
Javier Calvarro Nelson 5 лет назад
Родитель
Сommit
c729bc75ce

+ 11 - 0
src/Mvc/Mvc.ViewFeatures/src/RazorComponents/ComponentRenderer.cs

@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Components;
 using Microsoft.AspNetCore.Html;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc.Rendering;
+using Microsoft.Net.Http.Headers;
 
 namespace Microsoft.AspNetCore.Mvc.ViewFeatures
 {
@@ -87,6 +88,11 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
 
         private async Task<IHtmlContent> PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
         {
+            if (!context.Response.HasStarted)
+            {
+                context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, max-age=0";
+            }
+
             var currentInvocation = _serverComponentSerializer.SerializeInvocation(
                 invocationId,
                 type,
@@ -124,6 +130,11 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
 
         private IHtmlContent NonPrerenderedServerComponent(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
         {
+            if (!context.Response.HasStarted)
+            {
+                context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, max-age=0";
+            }
+
             var currentInvocation = _serverComponentSerializer.SerializeInvocation(invocationId, type, parametersCollection, prerendered: false);
 
             return new ComponentHtmlContent(_serverComponentSerializer.GetPreamble(currentInvocation));

+ 4 - 0
src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs

@@ -303,6 +303,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
             Assert.Equal(typeof(TestComponent).Assembly.GetName().Name, serverComponent.AssemblyName);
             Assert.Equal(typeof(TestComponent).FullName, serverComponent.TypeName);
             Assert.NotEqual(Guid.Empty, serverComponent.InvocationId);
+
+            Assert.Equal("no-cache, no-store, max-age=0", viewContext.HttpContext.Response.Headers[HeaderNames.CacheControl]);
         }
 
         [Fact]
@@ -344,6 +346,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
             Assert.Null(epilogueMarker.Sequence);
             Assert.Null(epilogueMarker.Descriptor);
             Assert.Null(epilogueMarker.Type);
+
+            Assert.Equal("no-cache, no-store, max-age=0", viewContext.HttpContext.Response.Headers[HeaderNames.CacheControl]);
         }
 
         [Fact]