ASP Net Core 3.1。 UseExceptionHandler不处理异常

时间:2020-07-08 08:46:48

标签: asp.net-core-mvc

我想使用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");
        }

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

0 个答案:

没有答案