Intro
This time, I will try using React for the client-side of my ASP.NET Core application.
I want to build the client-side code and the server-side code separately, because they will rarely be changed at the same time.
Environments
- .NET ver.9.0.100
- Microsoft.AspNetCore.SpaServices.Extensions ver.9.0.0
- Node.js ver.22.11.0
- React ver.18.3.1
Project file structures
OfficeFileAccessor - Root folder of ASP.NET Core application
L office-file-accessor - Root folder of React application
L React application files
L ASP.NET Core application files
UseSpa
I can also save the pre-built React code as static files in wwwroot directory and use it server-side.
However, in the debug environment, I want to access the page displayed at localhost:5173 as a result of running npm run dev, and in the release environment, I want to load the files from the dist folder.
To do this, I can use "UseSpa".
(I have to add Microsoft.AspNetCore.SpaServices.Extensions first).
Program.cs
using System.Text.Json.Serialization;
using Microsoft.Extensions.FileProviders;
using NLog;
using NLog.Web;
...
builder.Services.AddSpaStaticFiles(configuration =>
{
if (builder.Environment.EnvironmentName == "Development")
{
configuration.RootPath = "office-file-accessor";
}
else
{
configuration.RootPath = "office-file-accessor/dist";
}
});
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
var app = builder.Build();
app.UseRouting();
app.MapStaticAssets();
// To allow the application to load React files other than the index.html, such as JavaScript and CSS.
if (builder.Environment.EnvironmentName != "Development")
{
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "office-file-accessor/dist")),
RequestPath = ""
});
}
app.MapControllers();
app.UseSpa(spa =>
{
if (builder.Environment.EnvironmentName == "Development")
{
spa.Options.SourcePath = "office-file-accessor";
spa.UseProxyToSpaDevelopmentServer("http://localhost:5173");
}
else
{
spa.Options.SourcePath = "office-file-accessor/dist";
}
});
app.Run();
...
Top comments (0)