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

Kentico 13中UseStatusCodePagesWithReExecute与UseExceptionHandler兼容问题

在Kentico 13中协同使用ExceptionHandler和StatusCodePages中间件
  • 调整中间件顺序
    错误处理中间件必须在Kentico中间件之前配置,因为ASP.NET Core中间件按注册顺序执行,晚注册的中间件无法拦截已被前置中间件处理的请求。

  • 配置ExceptionHandler处理未捕获异常
    不要直接指定ExceptionHandlingPath,改用自定义逻辑将异常转为500状态码,并重新执行到ErrorController,避免覆盖正常状态码的处理流程:

    app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.Response.ContentType = "text/html";
    
            // 可选:记录异常日志
            var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>();
            if (exceptionFeature?.Error != null)
            {
                // _logger.LogError(exceptionFeature.Error, "未处理异常: {Path}", exceptionFeature.Path);
            }
    
            // 重新执行到ErrorController的500页面
            var originalPath = context.Request.Path;
            context.Request.Path = "/error/500";
            try
            {
                var invoker = context.RequestServices.GetRequiredService<IActionInvokerFactory>().CreateInvoker(context);
                await invoker.InvokeAsync();
            }
            finally
            {
                context.Request.Path = originalPath;
            }
        });
    });
    
  • 配置StatusCodePages处理所有状态码
    紧接着添加UseStatusCodePagesWithReExecute,让它接管404等非异常类状态码的处理:

    app.UseStatusCodePagesWithReExecute("/error/{0}");
    
  • 确保ErrorController正确返回状态码
    控制器Action必须设置响应状态码,避免浏览器收到200状态(误以为请求成功):

    [Route("error")]
    public class ErrorController : Controller
    {
        [Route("{statusCode}")]
        public IActionResult Index(int statusCode)
        {
            // 设置响应状态码与请求的错误码一致
            Response.StatusCode = statusCode;
    
            // 根据状态码返回对应视图
            var viewName = statusCode switch
            {
                404 => "NotFound",
                500 => "InternalServerError",
                _ => "Error"
            };
    
            return View(viewName);
        }
    }
    
  • 检查Kentico后台错误处理设置
    进入Kentico后台的设置 -> 系统 -> 错误处理,确保:

    • 若使用ASP.NET Core中间件处理错误,关闭Kentico的“显示自定义错误页面”选项;
    • 若保留Kentico设置,将自定义错误页面路径设置为/error/{0},与ASP.NET Core配置对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:26:16