Asp.net 如何将错误404路由到默认视图?

Asp.net 如何将错误404路由到默认视图?,asp.net,asp.net-mvc,asp.net-mvc-routing,Asp.net,Asp.net Mvc,Asp.net Mvc Routing,我在.NET Core 1.1中有一个项目,采用MVC架构, 我想在URL不正确时重定向(状态代码:404;未找到)

我在.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?}");
});
 app.UseMvc(routes =>
    {   routes.MapRoute(
             name: "Default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "IndexB" }
          );
     );
但如果在本项目中,有4个控制器,且在启动时有此配置:

app.UseMvc(routes =>
{     routes.MapRoute(
            name: "Default",
            template: "{controller=Home}/{action=GetDocument}/{id?}");
});
 app.UseMvc(routes =>
    {   routes.MapRoute(
             name: "Default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "IndexB" }
          );
     );
在HomeController或所有控制器上使用此代码(我已经尝试了这两种方法):

当另一个项目中的第一个代码像一个符咒一样工作时,它会去它必须去的地方,但如果不存在URL,则会转到错误页面


但是在这个有第二个代码的项目中,无论发生什么,我总是被重定向到错误页面。

如果重定向到404的默认视图,请在
Configure
method of
Startup.cs
文件中添加自定义中间件委托

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等)设置默认视图


我希望它能帮助您并让我知道是否需要更多信息。

如果您重定向到404的默认视图,请在
配置
启动.cs的
方法中添加自定义中间件委托

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等)设置默认视图


我希望它能帮助您,如果您需要更多信息,请告诉我。

我找到了两种处理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

另一种解决方案是使用内置的middlware StatusCodePagesMiddle软件。此中间件可用于处理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"); 
}

我找到了两种处理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

另一种解决方案是使用内置的middlware StatusCodePagesMiddle软件。此中间件可用于处理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"); 
}

为什么它仍然
.NET Core 1.1
?更新为2.2我正在一家公司实习,我必须这样做,但我不能全部改变,因为这需要做很多工作,而且我没有知识@TanvirArjelWhy it仍然
.NET Core 1.1
?将其更新为2.2我正在一家公司实习,我必须这样做,但我不能全部改变,因为这需要做很多工作,而且我没有知识@Tanvirarjelf关于明天早上工作中的更多细节,我将尝试一下,谢谢!明天早上在工作中,我将尝试更多细节,谢谢!明天早上上班我会试试,谢谢!工作起来很有魅力,我知道有一个简单的方法可以做到这一点,谢谢你明天早上上班我会试试的,谢谢!工作起来很有魅力,我知道有一个简单的方法可以做到,谢谢