代码之家  ›  专栏  ›  技术社区  ›  Tom Rushton

启动时路由错误。当ASP出现404或500错误时,cs不会重定向到控制器。NET核心MVC

  •  0
  • Tom Rushton  · 技术社区  · 2 年前

    我想要我的创业公司。cs类在发生404或500错误时重定向到我的错误控制器。

    创业。反恐精英

    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状态代码时设置的,路径在URL中不会更改。如何让它重定向到我的控制器,这样我就可以应用我的逻辑。

    错误控制器。反恐精英

        [Route("ErrorPages")]
    class ErrorController : Controller
    {        
        [Route("500")]
        public IActionResult AppError()
        {
            return View();
        }
    
        [Route("404")]
        public IActionResult PageNotFound()
        {
            return View("~/Views/404.cshtml");
        }
    }
    
    0 回复  |  直到 2 年前
        1
  •  0
  •   kyenry    2 年前

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

    在你的 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}");
            }
    

    你也可以选择 NotFound.cshtml 视图,您可以从中了解 ViewBag.ErrorMessage (注意:ASP.NET Core始终在中搜索Notfound操作。) AccountController.cs 但你可以在创业时改变这一点。(政务司司长)

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