-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
Copy pathSpaDefaultPageMiddleware.cs
74 lines (64 loc) · 3.02 KB
/
SpaDefaultPageMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace Microsoft.AspNetCore.SpaServices
{
internal class SpaDefaultPageMiddleware
{
public static void Attach(ISpaBuilder spaBuilder)
{
if (spaBuilder == null)
{
throw new ArgumentNullException(nameof(spaBuilder));
}
var app = spaBuilder.ApplicationBuilder;
var options = spaBuilder.Options;
// Rewrite all requests to the default page
app.Use((context, next) =>
{
// If we have an Endpoint, then this is a deferred match - just noop.
if (context.GetEndpoint() != null)
{
return next();
}
context.Request.Path = options.DefaultPage;
return next();
});
// Serve it as a static file
// Developers who need to host more than one SPA with distinct default pages can
// override the file provider
app.UseSpaStaticFilesInternal(
options.DefaultPageStaticFileOptions ?? new StaticFileOptions(),
allowFallbackOnServingWebRootFiles: true);
// If the default file didn't get served as a static file (usually because it was not
// present on disk), the SPA is definitely not going to work.
app.Use((context, next) =>
{
// If we have an Endpoint, then this is a deferred match - just noop.
if (context.GetEndpoint() != null)
{
return next();
}
var message = "The SPA default page middleware could not return the default page " +
$"'{options.DefaultPage}' because it was not found, and no other middleware " +
"handled the request.\n";
// Try to clarify the common scenario where someone runs an application in
// Production environment without first publishing the whole application
// or at least building the SPA.
var hostEnvironment = (IWebHostEnvironment)context.RequestServices.GetService(typeof(IWebHostEnvironment));
if (hostEnvironment != null && hostEnvironment.IsProduction())
{
message += "Your application is running in Production mode, so make sure it has " +
"been published, or that you have built your SPA manually. Alternatively you " +
"may wish to switch to the Development environment.\n";
}
throw new InvalidOperationException(message);
});
}
}
}