首页 > 解决方案 > ASP 网络核心 3.1。UseExceptionHandler 不处理异常

问题描述

我想使用 UseExceptionHandle 全局处理异常并将用户重定向到生产环境中的自定义错误页面。我发现在调用异步控制器动作方法时,重定向以可预测的方式发生。但是同步操作调用会导致抛出异常并停止应用程序。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {            
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
                app.UseHsts();
            }
            app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();            
            app.UseAuthentication();
            app.UseAuthorization();          
            app.UseEndpoints(endpoints =>
            {              
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");               
            });
        }

为了测试,我在同步和异步操作中抛出异常。

public async  Task<ViewResult> Index(string user)
        {
           throw new Exception("My Custom Exception");
        }

public ViewResult Index(string user)
        {
            throw new Exception("My Custom Exception");
        }

这种行为的原因可能是什么?

标签: asp.net-core-mvc

解决方案


推荐阅读