简体   繁体   English

Startup.cs 中的错误路由不会在 404 或 500 错误 ASP.NET Core MVC 时重定向到 controller

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

I want my startup.cs class to redirect to my Error controller when a 404 or 500 error occurs.当发生 404 或 500 错误时,我希望我的 startup.cs class 重定向到我的错误 controller。

Startup.cs启动.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);
  }

But when the content.Request.Path is set when a 404 or 500 status code is detected, the path does not change in the URL. How to I get this to redirect to my controller so I can then apply my logic.但是当检测到 404 或 500 状态代码时设置了 content.Request.Path 时,URL 中的路径不会改变。如何将其重定向到我的 controller,以便我可以应用我的逻辑。

ErrorController.cs错误控制器.cs

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

    [Route("404")]
    public IActionResult PageNotFound()
    {
        return View("~/Views/404.cshtml");
    }
}

For that you need an error controller为此,您需要一个错误 controller

in your ErrorController.cs file在您的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");
    }
}

In your startup.cs file在你的 startup.cs 文件中

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

you can also have your NotFound.cshtml view, which you can be listening for the value of ViewBag.ErrorMessage ( Note: ASP.NET Core always searches for the Notfound action in AccountController.cs but you can change that in your startup.cs )你也可以有你的NotFound.cshtml视图,你可以监听ViewBag.ErrorMessage的值(注意:ASP.NET Core 总是在AccountController.cs中搜索 Notfound 操作,但你可以在你的 startup.cs 中更改它)

and then you can also continue the case switch statement to suit all the status code errors you're planning to intercept然后您还可以继续 case switch 语句以适应您计划拦截的所有状态代码错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM