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

集成Identity的ASP.NET Core 6 MVC项目自定义404错误页面配置求助

ASP.NET Core 6 MVC 自定义404错误页面实现方案

针对集成Identity的ASP.NET Core 6 MVC项目,以下是两种可靠的自定义404错误页面实现方式,适配你提到的类似Identity AccessDenied页面的模式:


方法一:使用UseStatusCodePagesWithReExecute(推荐,URL保持不变)

这种方式是服务器端转发请求到错误控制器,浏览器URL不会改变,体验更友好,和Identity的错误页面逻辑一致。

1. 配置Program.cs中间件

注意中间件顺序,必须放在UseStaticFiles、UseRouting之前,UseExceptionHandler之后:

var builder = WebApplication.CreateBuilder(args);

// 保留你现有的MVC和Identity服务配置
builder.Services.AddControllersWithViews();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

var app = builder.Build();

// 异常处理(针对500等未捕获错误)
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

// 配置状态码页面转发规则
app.UseStatusCodePagesWithReExecute("/Error/{0}");

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

// 保留现有路由配置
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages(); // Identity依赖此路由

app.Run();

2. 创建Error控制器

在Controllers目录下新增ErrorController.cs,处理不同状态码的错误请求:

public class ErrorController : Controller
{
    public IActionResult Index(int? statusCode)
    {
        // 根据状态码返回对应视图
        switch (statusCode)
        {
            case 404:
                ViewData["Title"] = "404 - 页面未找到";
                return View("NotFound");
            default:
                ViewData["Title"] = "服务器错误";
                return View();
        }
    }
}

3. 创建自定义404视图

在Views/Error目录下新增NotFound.cshtml,编写自定义页面内容:

@{
    Layout = "_Layout"; // 复用项目主布局
}

<div class="container mt-5">
    <h1 class="text-danger">404</h1>
    <h3>抱歉,您访问的页面不存在或已被移除</h3>
    <p><a asp-action="Index" asp-controller="Home" class="btn btn-primary">返回首页</a></p>
</div>

方法二:直接配置静态错误页面(简单场景)

如果不需要动态处理状态码,可直接指定静态视图路径:

1. 修改Program.cs配置

替换UseStatusCodePagesWithReExecute为以下代码:

app.UseStatusCodePages(async context =>
{
    var response = context.HttpContext.Response;
    if (response.StatusCode == 404)
    {
        response.Redirect("/Error/NotFound");
    }
});

2. 复用方法一中的ErrorController和NotFound.cshtml即可


注意事项

  • 开发环境下,默认的开发者异常页面会覆盖自定义错误页,若需测试可临时注释UseDeveloperExceptionPage(如果你的代码里有)。
  • 确保静态文件的404也能被捕获:UseStatusCodePagesWithReExecute必须放在UseStaticFiles之前。
  • 若项目混合了Razor Pages(Identity依赖),确保MapRazorPages()路由配置存在。

内容的提问来源于stack exchange,提问作者max ray

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:27:04