I'm trying to modify an existing ASP.NET Core Angular 8 app to build and run in production mode in order to use the serviceWorkers. So I've followed the recommandation in this article. I'm also generating source maps according to this article.
I modified my project to run "npm run build -- --prod --source-map" by modifiying the project file and add:
<Target Name="BuildAngular" BeforeTargets="Build">
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --prod --source-map" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod --source-map" Condition="'$(BuildServerSideRenderer)'=='true'" />
</Target>
I've also modified the startup.cs code to no longer use
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
So now I have:
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";
});
I've also modified the debug configuration to start the program instead of starting IIS. I'm still launching the browser. I'm no longer running "npm start" in a powershell window in the clientApp directory.
Everything seems to build fine, the program starts and displays:
Hosting environment: Dev
Content root path: C:\Users\olivier.matrot\source\repos\SafeProtect\WebAdministration\SafeProtect.WebAdmin.Web
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
The browser starts and try to open localhost:5001. Then it immediatly pops:
An error occurred: Cannot read property 'nativeElement' of null URL: /
What is going on here?
EDIT: Here is the Configure code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
try
{
this.logger.Format(SeverityLevel.Info, "[Configure]");
// else if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Dev") || env.IsEnvironment("Test"))
if (env.IsDevelopment())
{
app.UseDatabaseErrorPage();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
// application.UseFileServer();
app.UseSession();
app.UseJwtBearerTokens(
app.ApplicationServices.GetRequiredService<IOptions<TokenProviderOptions>>(),
PrincipalResolver);
// -------------------------------------------------------------
IList<CultureInfo> supportedCultures = new List<CultureInfo>()
{
new CultureInfo("fr-FR"),
new CultureInfo("en-US"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("fr-FR"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures,
});
// -------------------------------------------------------------
// app.UseMvc(routes =>
// {
// routes.MapRoute(
// name: "default",
// template: "{controller}/{action=Index}/{id?}");
// });
app.UseMvc(routes =>
{
routes.MapRouteAnalyzer("/routes");
routes.MapRoute("default", "api/{controller}/{action}/{id?}");
});
// To get the IP Address of the client in controllers
// https://stackoverflow.com/a/41335701/15186
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto,
});
app.UseAuthentication();
// -------------------------------------------------------------
app.UseCors(x => x
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseRouting();
// -------------------------------------------------------------
// Create a real-time comunication application
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ServerHub>("/serverhub");
});
// Warning, the use of SignalR must be set before UseSpa otherwise you'll get a negotiation error (404) when connecting to the hub.
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");
// spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
}
});
// -------------------------------------------------------------
// Handle errors
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = MediaTypeNames.Application.Json;
var exception = context.Features.Get<IExceptionHandlerFeature>();
if (exception != null)
{
SafeProtectLogHelper.Instance.WebApiLogger.WriteException(exception.Error, SeverityLevel.Error);
await context.Response
.WriteAsync(JsonConvert.SerializeObject(exception.Error?.Message))
.ConfigureAwait(continueOnCapturedContext: false);
}
});
});
// Allow the controllers to read the browser supported cultures
app.UseRequestLocalization();
// applicationLifetime.ApplicationStarted.Register(() =>
// {
// var infos = routeAnalyzer.GetAllRouteInformations();
// var category = @"RouteAnalyzer";
// this.logger.Write(category, SeverityLevel.Debug, "======== BEGIN DUMP ALL ROUTE INFORMATION ========");
// foreach (var info in infos)
// {
// this.logger.Write(category, SeverityLevel.Debug, info.ToString());
// }
// this.logger.Write(category, SeverityLevel.Debug, "======== END DUMP ALL ROUTE INFORMATION ========");
// });
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.logger.Format(this.logger.DefaultCategory, this.logger.DefaultTrackInfo, ex.ToString(), SeverityLevel.Error, "Configure => Unexpected exception : {0}", ex.Message);
}
}