Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to host an Angular app inside .NET Core 3.1 WebAPI?

I want to provide my Angular app through the root route / and the REST API through /api/*. For the Angular routing I have to redirect all requests to /index.html except the requests for existing files (e.g. media files) and my API controller routes.

With the Startup.cs below it's close to be working:

  • Opening http://localhost:5000 will return the index.html and the angular routing is working, that I get redirected to http://localhost:5000/home
  • API calls are still working
  • Existing CSS/JavaScript files are returned

The following is not working: Refreshing or opening directly http://localhost:5000/home will end up in a 404. I guess /home is not redirected to the index.html. What I'm missing here?

public class Startup
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public Startup(IWebHostEnvironment webHostEnvironment)
    {
      _webHostEnvironment = webHostEnvironment;
    }
    public void ConfigureServices(IServiceCollection services)
    {        
      services.AddSpaStaticFiles(options =>
      {
        options.RootPath = "wwwroot";
      });

      services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      app.UseDefaultFiles();
      app.UseSpaStaticFiles();
      app.UseCors();
      app.UseSwagger();
      app.UseSwaggerUI(c => { /*...*/ });
      app.UseRouting();
      app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}
like image 265
Joba Avatar asked May 27 '20 22:05

Joba


People also ask

Can you use Angular with .NET Core?

The updated Angular project template provides a convenient starting point for ASP.NET Core apps using Angular and the Angular CLI to implement a rich, client-side user interface (UI). The template is equivalent to creating an ASP.NET Core project to act as an API backend and an Angular CLI project to act as a UI.

How do I run a .NET Core in Angular app?

To start the project, press F5 or select the Start button at the top of the window. You will see two command prompts appear: The ASP.NET Core API project running. The Angular CLI running the ng start command.

How do I connect ASP NET Core to angular?

Summary First, create your ASP.NET Core Web API. To do that just follow the steps below. Select File > New > Project. Select ASP.NET Core Web Application. Name the project AngularDemo to have the same namespace as my project. Click OK. Select ASP.NET Core with Angular and then uncheck Configure for HTTPS.

How do I create a web API with AngularJS?

First, create your ASP.NET Core Web API. To do that just follow the steps below. Select File > New > Project. Select ASP.NET Core Web Application. Name the project AngularDemo to have the same namespace as my project. Click OK. Select ASP.NET Core with Angular and then uncheck Configure for HTTPS.

How to deploy ASP NET Core WebAPI project to shared hosting?

With the above files ready, we can xcopy the entire "dist" folder to "app" folder on shared hosting via FTP ( FileZilla ). 2. Publish & Deploy ASP.NET Core WebAPI Project Right click on ASP.NET Core WebAPI project in Visual Studio and click on Publish which brings the following screen. Configure the values as shown here:

What is the best way to build angular apps?

There are so many ways we can build Angular apps and ship them for production. One way is to build Angular with Nodejs, Java, or .NET and another way is to build the angular and serve that static content with NGINX web server. With .NET we have to deal with the server code as well, for example, you need to load the index.html page with .NET core


Video Answer


2 Answers

I had the same problem but app.UseSpa(...) did not work as I guess I was missing some dependecies.

Alternativele you could add endpoints.MapFallbackToFile("/index.html"); in app.UseEndpoints(..), which is part of the Microsoft.AspNetCore.StaticFiles assembly.

So it would look like this:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("/index.html");
});

Source: https://weblog.west-wind.com/posts/2020/Jul/12/Handling-SPA-Fallback-Paths-in-a-Generic-ASPNET-Core-Server#server-side-navigation-of-client-side-routes

like image 94
Mathias Avatar answered Oct 23 '22 21:10

Mathias


Your are missing one important thing for SPA hosting:

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
});

Handles all requests from this point in the middleware chain by returning the default page for the Single Page Application (SPA).

This middleware should be placed late in the chain, so that other middleware for serving static files, MVC actions, etc., takes precedence.

- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.spaapplicationbuilderextensions.usespa


Update: If you only want to map a specific route to the index.html i.e. everything starting with http://localhost/ui/ you can combine it with app.MapWhen

app.MapWhen(
    context => context.Request.Path.StartsWithSegments("/ui/", StringComparison.OrdinalIgnoreCase), 
    cfg => 
    {
        cfg.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501
        });
    }
);
like image 29
Maximilian Ast Avatar answered Oct 23 '22 20:10

Maximilian Ast