I will create a custom 404 page as shown in a few examples I found on Stackoverflow. However, even as I type the text in the url, the relevant checks are triggered. I don't understand if this is because I am in debug or if there is a different reason. I added the codes of the relevant fields and shared a video.
I would be happy if you could help me.
https://www.veed.io/view/0a67ae93-44b1-46b8-a9a0-9880316bc40f?panel=share
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllersWithViews()
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStatusCodePagesWithRedirects("/Error/{0}");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
ErrorController.cs
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace SFMS.Controllers
{
public class ErrorController : Controller
{
[Route("Error/{statusCode}")]
public IActionResult Error(int? statusCode)
{
Debug.WriteLine(statusCode);
if (statusCode.HasValue)
{
if (statusCode == 404)
{
return View("PageNotFound");
}
else
{
return View("Index");
}
}
return View();
}
public IActionResult PageNotFound()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Index()
{
return View();
}
}
}
ASP.Net Core Custom Error Page triggered multiple times
I checked your code in a new MVC application, your code worked fine and the custom error page was triggered only once. You could create a new MVC application and add a break point in the ErrorController Error method to debug the code.
However, even as I type the text in the url, the relevant checks are triggered. I don't understand if this is because I am in debug or if there is a different reason.
By default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body.
According to your video, when you access the site via https://localhost:{port}/aaa
, since the endpoint does not exist, it will return a 404-error page (without using the UseStatusCodePages middleware):
Then, to enable default/custom text-only handlers for common error status codes, we could use the UseStatusCodePages
middleware. In your code you are using the UseStatusCodePagesWithRedirects
middleware, it will capture the default 404 error and redirect to the Error controller with the status Code. If you set the break point in the Error code, you can see it:
and if using F12 developer tool to check the Network, you can see the UseStatusCodePagesWithRedirects extension method:
More detail information, see Handle errors in ASP.NET Core.