【问题标题】:How to route Error 404 to a default View?如何将错误 404 路由到默认视图?
【发布时间】:2019-09-01 22:45:03
【问题描述】:

我有一个 .NET Core 1.1 的 MVC 架构项目, 并且我想在 URL 不正确时重定向(状态代码:404;未找到)以重定向到我已经创建的错误视图。

在另一个只有一个控制器的项目中,我让它正常工作:

        [Route ("/Home/Error")]
        public IActionResult Error()
        {
            ViewBag.Title = "About Us";

            return View();
        }
        [Route("/{a}/{*abc}")]
        [HttpGet]
        public IActionResult Err(string a)
        {
            return RedirectToAction("Error", "Home");
        }

并在启动阶段:

app.UseMvc(routes =>
{     routes.MapRoute(
            name: "Default",
            template: "{controller=Home}/{action=GetDocument}/{id?}");
});

但是如果在这个项目中,有 4 个控制器,在启动时使用这个配置:

 app.UseMvc(routes =>
    {   routes.MapRoute(
             name: "Default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "IndexB" }
          );
     );

HomeController 或所有控制器上的这段代码(我都试过了):

        [Route("/Home/Error")]
        public IActionResult Error()
        {
            ViewBag.Title = "About Us";

            return View();
        }
        [Route("/{a}/{*abc}")]
        [HttpGet]
        public IActionResult Err(string a)
        {
            return RedirectToAction("Error", "Home");
        }

在另一个项目中的第一个代码就像一个魅力,它去它必须去的地方,但不存在的 URL 去错误页面。

但是在这个项目中使用第二个代码,无论如何我总是被重定向到错误页面。

【问题讨论】:

  • 为什么还是.NET Core 1.1??更新到2.2
  • 我正在一家公司实习,我必须这样做,但我无法改变这一切,因为工作量很大而且我没有相关知识。 @TanvirArjel

标签: asp.net asp.net-mvc asp.net-mvc-routing


【解决方案1】:

如果您重定向到 404 的默认视图,则在 Startup.cs 文件的 Configure 方法中添加自定义中间件委托。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        app.Use(async (context, next) =>
        {
            await next();
            if (context.Response.StatusCode == 404)
            {
                context.Request.Path = "/home/notfound";
                await next();
            }
        });

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
}

app.Use(async (context, next) => ... 是您的 中间件委托,它检查您的响应状态码是否为 404,然后设置重定向 context.Request.Path = "/home/notfound"; 的默认路径。您还可以为其他状态代码(如 500 等)设置默认视图。

我希望它对您有所帮助,如果需要更多信息,请告诉我。 :)

【讨论】:

  • 明天早上上班我试试,谢谢!
  • 就像一个魅力,我知道有一个简单的方法,谢谢
【解决方案2】:

我找到了两种处理 404 错误的方法。事实上,使用这些解决方案,您可以处理任何 HTTP 状态代码错误。为了处理错误,两种解决方案都使用 Startup.cs 类的 configure() 方法。对于不了解 Startup.cs 的人来说,它是应用程序本身的入口点。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();
    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home"; 
            await next();
        }
    });

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();
    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

解决方案 2

另一种解决方案是使用内置的中间件 StatusCodePagesMiddleware。此中间件可用于处理介于 400 和 600 之间的响应状态代码。此中间件允许返回通用错误响应或允许您还重定向到任何控制器操作或其他中间件。请参阅下面此中间件的所有不同变体。

app.UseStatusCodePages();

现在要处理 404 错误,我们将使用 app.UseStatusCodePagesWithReExecute 接受您希望重定向的路径。

app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");
public IActionResult Errors(string errCode) 
{ 
  if (errCode == "500" | errCode == "404") 
  { 
    return View($"~/Views/Home/Error/{errCode}.cshtml"); 
  }

  return View("~/Views/Shared/Error.cshtml"); 
}

【讨论】:

猜你喜欢
  • 2015-01-02
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 2017-07-07
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多