Reputation: 29484
I've got a .NET Core 6 Web API and a separate React frontend.
I could deploy them separately into separate subdomains.
But is there a way to combine them into 1 single domain?
Upvotes: 0
Views: 1934
Reputation: 1498
I think it has multiple domains only on Development. If you publish project to IIS website - you will be able to use single domain. Also you can attach to IIS process if want to debug in single domain mode. Downside is that JS is already minified in this case.
Upvotes: 0
Reputation: 124
You can simply create a build of your react project and then put it inside the wwwroot
folder. If the wwwroot
folder is not available, You can create one.
Then, Simply put this code to the end of the pipeline before app.Run()
in Program.cs
:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// route non-api urls to index.html
endpoints.MapFallbackToFile("/index.html");
});
Also do comment this line:
app.MapControllers();
Here's the original link for your reference.
How To deploy asp.net core web api project with react(standalone) in visual studio 2022
Upvotes: 0
Reputation: 4637
That is definitely possible. There are some predefined Visual Studio templates that setup SPA apps like that, but if you already have a Web API project it can be manually setup the same way.
Move your React client app folder into a sub directory in your Web API project. The sub directory name can be anything, but for this example lets call it ClientApp
.
This step gets your development environment setup so that anytime you run your project, to also jump start the React client app server as well.
In your Web API project, install the following NuGet packages in it:
Also in your Web API project, we'll want to add the following configuration into it:
<PropertyGroup>
...
<SpaRoot>ClientApp</SpaRoot>
<SpaProxyServerUrl>http://localhost:3000</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm serve</SpaProxyLaunchCommand>
...
</PropertyGroup>
SpaRoot
being the same folder name we created in step 1.SpaProxyServerUrl
is set to here. This is how Visual Studio will know that your client app is available and launch a browser to.There are a couple things you can do to prepare a production build with this setup.
Have your production build
NPM script output the compiled React app to the wwwroot
folder. Create this folder in your Web API project if it does not already exist.
Add at the very end of the request pipeline in your Program.cs
, add a call to fallback to the default web files (i.e. Index.html) with the following statement:
// Serve up the standard [Index.html] file that is typically created for SPA apps (Angular and React) app.UseDefaultFiles();
Upvotes: 4