UseStaticFiles() method adds StaticFiles middleware into the request pipeline. The UseStaticFiles is an extension method included in the StaticFiles middleware so that we can easily configure it. Now, open the browser and send http request http://localhost:<port>/default.html which will display default.
UseSpaStaticFiles(IApplicationBuilder) Configures the application to serve static files for a Single Page Application (SPA). The files will be located using the registered ISpaStaticFileProvider service.
NET Core is a runtime. It can execute applications that are built for it. ASP.NET Core is a collection of libraries that form a Framework for building web applications.
UseDefaultFiles is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware via UseStaticFiles to serve the file. Based on this, it's important to first setup the URL rewriter ( UseDefaultFiles ) before serving the actual file ( UseStaticFiles ).
Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients. Some configuration is required to enable serving of these files.
UseStaticFiles - Serve files inside of web root (wwwroot folder)
UseSpaStaticFiles - Serve static file like image, css, js in asset folder of angular app
UseSpa - let asp.net core know which directory you want to run your angular app, what dist folder when running in production mode and which command to run angular app in dev mode
Example
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
throw new InvalidOperationException($"To use {nameof(UseSpaStaticFiles)}, you must " +
$"first register an {nameof(ISpaStaticFileProvider)} in the service provider, typically " +
$"by calling services.{nameof(AddSpaStaticFiles)}.");
So you need to call app.AddSpaStaticFiles() to register default ISpaStaticFileProvider
Actually UseSpaStaticFiles and UseSpa both internally call the same method UseSpaStaticFilesInternal but with a different value for the 3rd parameter which is allowFallbackOnServingWebRootFiles. That is the reason why UseSpaStaticFiles throws an exception if no ISpaStaticFileProvider was registered it simply does not allow to fall back to wwwroot.
BTW if UseSpa falls back to wwwroot internally it calls old good app.UseStaticFiles(staticFileOptions);
Links to github sources: 1. SpaDefaultMiddleware 2. SpaStaticFilesExtensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With