启动中的错误路由.cs不会在核心 MVC 出现 404 或 500 错误时重定向到控制器 ASP.NET

Error routing in Startup.cs wont redirect to controller upon 404 or 500 error ASP.NET Core MVC

提问人:Tom Rushton 提问时间:4/28/2022 最后编辑:Tom Rushton 更新时间:4/28/2022 访问量:553

问:

我希望我的启动 .cs 类在发生 404 或 500 错误时重定向到我的错误控制器。

启动 .cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpContextAccessor accessor)
  {
     if (env.IsDevelopment())
     {
        app.UseDeveloperExceptionPage();
        app.UseExceptionHandler("/ErrorPages/500");
     }
     app.UseRouting();
     app.UseAuthentication();
     app.UseAuthorization();
     app.UseIPRestrictionService();
     app.Use(async (content, next) =>
     {
        await next();
        if (content.Response.StatusCode == 404 && !content.Response.HasStarted)
        {
            content.Request.Path = "/ErrorPages/404";
            await next();
        }
        if (content.Response.StatusCode == 500)
        {
            content.Request.Path = "/500";
            await next();
        }
     });
     app.UseHttpsRedirection();
     app.UseStaticFiles();
     app.UseEndpoints(endpoints =>
     {
        endpoints.MapContent();
        endpoints.MapControllers();
     });


     ContentExtensions.SetHttpContextAccessor(accessor);
     VisitorGroupManager.SetHttpContextAccessor(accessor);
     PageExtensions.SetHttpContextAccessor(accessor);
     //IsAuthenticatedCriterion.SetHttpContextAccessor(accessor);
  }

但是当内容。当检测到 404 或 500 状态代码时,设置 Request.Path,URL 中的路径不会更改。我如何让它重定向到我的控制器,这样我就可以应用我的逻辑。

错误控制器 .cs

    [Route("ErrorPages")]
class ErrorController : Controller
{        
    [Route("500")]
    public IActionResult AppError()
    {
        return View();
    }

    [Route("404")]
    public IActionResult PageNotFound()
    {
        return View("~/Views/404.cshtml");
    }
}
C# ASP.NET-MVC 错误处理

评论


答:

0赞 kyenry 4/28/2022 #1

为此,您需要一个错误控制器

在您的文件中ErrorController.cs

public class ErrorController : Controller
{
    private readonly ILogger<ErrorController> logger;

    public ErrorController(ILogger<ErrorController> logger)
    {
        this.logger = logger;
    }

    [Route("Error/{statusCode}")]
    public IActionResult HttpStatusCodeHandler(int statusCode)
    {
        var viewToReturn = string.empty;
        var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
        switch (statusCode)
        {
            case 404:
                ViewBag.ErrorMessage = "Sorry the resource you requested could not be found";
                logger.LogWarning($"404 Error Occured. Path = {statusCodeResult.OriginalPath}" + $"and QueryString = {statusCodeResult.OriginalQueryString}");
                viewToReturn = nameof(Notfound);
                break;
        }

        return View(viewToReturn ?? "defaultUnInterceptedErrorView");
    }

    [Route("Error")]
    [AllowAnonymous]
    public IActionResult Error()
    {
        var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        logger.LogError($"The Path {exceptionDetails.Path} threw an exception" + $"{exceptionDetails.Error}");
        return View("Error");
    }
}

在启动 .cs 文件中

if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseStatusCodePagesWithReExecute("/Error/{0}");
        }

你也可以拥有你的视图,你可以监听 ( 注意:ASP.NET Core 始终搜索 Notfound 操作,但你可以在启动时更改它.cs )NotFound.cshtmlViewBag.ErrorMessageAccountController.cs

然后,您还可以继续 case switch 语句,以适应您计划拦截的所有状态代码错误