对于未定义的路由,MVC 6没有异常抛出

use*_*516 8 .net c# asp.net-mvc

我有一个非常基本的asp.net MVC 6应用程序与基本路由,我有一个自定义ErrorController将错误路由到某些视图.

但我希望当用户键入不存在的URL时,会抛出异常(我可以处理它).但是,当我输入一些随机URL时,不会抛出任何异常,我只是得到一个空白页面.我很确定这在MVC <6中同样有效.

如果我只是在控制器中抛出异常,错误处理本身工作正常.

Startup.cs(部分)

public void Configure(IApplicationEnvironment appEnv, IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler(HandleException);
    }
    app.UseStaticFiles();
    app.UseMvc(routes => MapRoutes(routes, appEnv));
}


private static void MapRoutes(IRouteBuilder routes, IApplicationEnvironment env)
{
    routes.MapRoute(
       name: "default",
       template: "{controller}/{action}/{id?}",
       defaults: new { controller = "main", action = "index" });          
}

private static void HandleException(IApplicationBuilder errorApp)
{
    #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
    errorApp.Run(async context => HandleErrorContext(context));
    #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
}

private static void HandleErrorContext(HttpContext context)
{
    var error = context.Features.Get<IExceptionHandlerFeature>();
    var exception = error.Error;
    if (exception == null)
    {
        context.Response.Redirect("../error/external");
    }
    else if (exception is ExpirationException)
    {
        context.Response.Redirect("../error/expired");
    }
    else if (exception is HttpException)
    {
        var httpException = exception as HttpException;
        int code = httpException.GetHttpCode();
        context.Response.Redirect("../error/external?code=" + code);
    }
    else
    {
        context.Response.Redirect("../error/external");
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*516 1

不是我的问题的直接答案,但我已经从/sf/answers/338346361/找到了解决方法。我仍然想知道为什么 ASP.NET 不抛出 404。

           routes.MapRoute(
                "PageNotFound",
                "{*catchall}",
                new { controller = "Home", action = "PageNotFound" }
                );
Run Code Online (Sandbox Code Playgroud)