You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core自定义错误页多次触发问题求助

自定义404页面输入URL时提前触发的问题

我参考StackOverflow上的示例做了自定义404页面,但在输入URL文本的过程中,相关的404检测就被触发了。不清楚这是Debug模式导致的,还是有其他原因。以下是相关代码:

Program.cs 代码

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

内容的提问来源于stack exchange,提问作者Ozgur Saklanmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:47:21