Skip to content

Commit 0c77224

Browse files
Allow prerendering middleware to pass through non-prerendered responses (important when using dev middleware)
1 parent a83ec3a commit 0c77224

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed

src/Microsoft.AspNetCore.SpaServices.Extensions/Prerendering/SpaPrerenderingExtensions.cs

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -113,21 +113,19 @@ public static void UseSpaPrerendering(
113113
context.Response.Body = originalResponseStream;
114114
}
115115

116-
// If it's not a success response, we're not going to have any template HTML
117-
// to pass to the prerenderer.
118-
if (context.Response.StatusCode < 200 || context.Response.StatusCode >= 300)
116+
// If it isn't an HTML page that we can use as the template for prerendering,
117+
// - ... because it's not text/html
118+
// - ... or because it's an error
119+
// then prerendering doesn't apply to this request, so just pass through the
120+
// response as-is. Note that the non-text/html case is not an error: this is
121+
// typically how the SPA dev server responses for static content are returned
122+
// in development mode.
123+
var canPrerender = IsSuccessStatusCode(context.Response.StatusCode)
124+
&& IsHtmlContentType(context.Response.ContentType);
125+
if (!canPrerender)
119126
{
120-
var message = $"Prerendering failed because no HTML template could be obtained. " +
121-
$"Check that your SPA is compiling without errors. " +
122-
$"The {nameof(SpaApplicationBuilderExtensions.UseSpa)}() middleware returned " +
123-
$"a response with status code {context.Response.StatusCode}.";
124-
if (outputBuffer.Length > 0)
125-
{
126-
message += " and the following content: "
127-
+ Encoding.UTF8.GetString(outputBuffer.GetBuffer());
128-
}
129-
130-
throw new InvalidOperationException(message);
127+
await outputBuffer.CopyToAsync(context.Response.Body);
128+
return;
131129
}
132130

133131
// Most prerendering logic will want to know about the original, unprerendered
@@ -160,6 +158,20 @@ public static void UseSpaPrerendering(
160158
});
161159
}
162160

161+
private static bool IsHtmlContentType(string contentType)
162+
{
163+
if (string.Equals(contentType, "text/html", StringComparison.Ordinal))
164+
{
165+
return true;
166+
}
167+
168+
return contentType != null
169+
&& contentType.StartsWith("text/html;", StringComparison.Ordinal);
170+
}
171+
172+
private static bool IsSuccessStatusCode(int statusCode)
173+
=> statusCode >= 200 && statusCode < 300;
174+
163175
private static void RemoveConditionalRequestHeaders(HttpRequest request)
164176
{
165177
request.Headers.Remove(HeaderNames.IfMatch);

0 commit comments

Comments
 (0)