【问题标题】:Generic Exception Filter to Display error message on Specific Controller Action's View通用异常过滤器在特定控制器操作的视图上显示错误消息
【发布时间】:2023-04-11 07:14:03
【问题描述】:
[HttpPost]
public IActionResult DoSomething(Some thing)
{
  try
  {
     return View (message);
  }
  catch (Exception) { return View (message); }
}

我想捕获异常并希望将自定义错误消息传递给视图。我不想在每个操作方法中添加 try catch 块。有没有办法在 controller 操作中全局捕获异常并获取异常,并将错误消息返回到特定操作的 View。 IE。我不想全局捕获异常并最终进入错误页面。 如果有人给我一个概述或基本想法,那将非常有帮助。

【问题讨论】:

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


    【解决方案1】:

    根据你的描述,我建议你可以考虑使用app.UseExceptionHandler("/Home/Error");来达到你的要求。

    ExceptionHandler 可以捕获你的控制器代码抛出的异常,然后它会重写到 Home 错误动作,而不是直接返回到客户端。

    更多使用方法,可以参考以下代码:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
            app.UseExceptionHandler("/Home/Error");
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
            app.UseSession();   
            app.UseAuthentication();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
             });
        }
    

    错误动作代码:

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    

    另外如果你想自定义这个ExceptionHandler,我建议你可以参考这个answer。我制作了一个自定义异常处理程序中间件并重写了对错误操作方法的响应。

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多