I am working on a custom error page for non-development environments. While working on this custom page, I set environment to "Staging" in launchSettings.json file. When I switched the setting back to "Development" and restarted the app, it only showed the generic error page (see following screenshot.)
I run the trace in program.cs and did see the it was using the default exception handler middleware: app.UseExceptionHandler("/Error");
I even existed the IDE and started again. But the detailed error page was no longer working. I could not figure out what caused this to happen and unable to resolved it. Please help! (see more details in following sections)
TESTING INFO:
App Type: ASP .NET6 with razor pages
IDE: VS 2022
Dev machine: Windows 11
Using IIS Express to view web pages
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:16950",
"sslPort": 44324
}
},
"profiles": {
"WebProtectConnString": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7074;http://localhost:5074",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "development"
}
}
}
}
ERROR HANDLING CONFIG (in program.cs)
if (app.Environment.IsDevelopment())
{
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();
}
else
{
app.UseExceptionHandler("/Exceptions/ErrorHandler");
}
CodePudding user response:
By default, in Program.cs file of a .net 6 project, if (!app.Environment.IsDevelopment())
is the default code, but in your code snippet, it's if (app.Environment.IsDevelopment())
, this means when you set Development
in the launchSettings.json
, your application will execute this 2 lines
app.UseExceptionHandler("/Error");
app.UseHsts();
And when execute app.UseExceptionHandler("/Error");
with an unhandled exception, the Error.cshtml
will appear.. That's the reason you saw the page in your screenshot.
Since you want to use a custom view for non-development environments, you may need to remove app.UseExceptionHandler("/Error");
and write code below, this will make your app show exception message directly in development stage and show your custom view in other stages:
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Exceptions/ErrorHandler");
app.UseHsts();
}else{ //leave the else empty, then exception will show in browser directly }