Asp.Net Core中有哪些异常处理

1.继承Controller,重写OnActionExecuted

默认都会继承一个Controller类,重写OnActionExecuted,添加上异常处理即可。一般情况下我们会新建一个BaseController, 让所有Controller继承BaseController。代码如下

复制代码
 1 public class BaseController : Controller
 2 {
 3     public override void OnActionExecuted(ActionExecutedContext context)
 4     {
 5         var exception = context.Exception;
 6         if (exception != null)
 7         {
 8             context.ExceptionHandled = true;
 9             context.Result = new ContentResult
10             {
11                 Content = $"BaseController错误 : { exception.Message }"
12             };
13         }
14         base.OnActionExecuted(context);
15     }
16 }
复制代码

 

2.使用 ActionFilterAttribute。

ActionFilterAttribute是一个特性,本身实现了 IActionFilter 及 IResultFilter , 所以不管是action里抛错,还是view里抛错,理论上都可以捕获。我们新建一个 ExceptionActionFilterAttribute, 重写 OnActionExecuted及OnResultExecuted,添加上异常处理,完整代码如下:

复制代码
 1 public class ExceptionActionFilterAttribute:ActionFilterAttribute
 2 {
 3     public override void OnActionExecuted(ActionExecutedContext context)
 4     {
 5         var exception = context.Exception;
 6         if (exception != null)
 7         {
 8             context.ExceptionHandled = true;
 9             context.Result = new ContentResult
10             {
11                 Content = $"错误 : { exception.Message }"
12             };
13         }
14         base.OnActionExecuted(context);
15     }
16 
17     public override void OnResultExecuted(ResultExecutedContext context)
18     {
19         var exception = context.Exception;
20         if (exception != null)
21         {
22             context.ExceptionHandled = true;
23             context.HttpContext.Response.WriteAsync($"错误 : {exception.Message}");
24         }
25         base.OnResultExecuted(context);
26     }
27 }
复制代码

 

使用方式有两种,
在controller里打上 [TypeFilter(typeof(ExceptionActionFilter)] 标签;

在Startup.cs里以filter方式全局注入。

1 public void ConfigureServices(IServiceCollection services)
2 {
3     services.AddControllersWithViews(options =>
4   {
5       options.Filters.Add<ExceptionActionFilterAttribute>();
6   })
7 }

 

3.使用 IExceptionFilter

我们知道, Asp.Net Core提供了5类filter, IExceptionFilter是其中之一,顾名思义,这就是用来处理异常的。Asp.net Core中ExceptionFilterAttribute已经实现了IExceptionFilter,所以我们只需继承ExceptionFilterAttribute,重写其中方法即可。 同样新建CustomExceptionFilterAttribute继承 ExceptionFilterAttribute,重写 OnException ,添加异常处理,完整代码如下:

复制代码
1 public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
2 {
3     public override void OnException(ExceptionContext context)
4     {
5         context.ExceptionHandled = true;
6         context.HttpContext.Response.WriteAsync($"CustomExceptionFilterAttribute错误:{context.Exception.Message}");
7         base.OnException(context);
8     }
9 }
复制代码

 

4.使用ExceptionHandler

在 startup.cs 里,vs新建的项目会默认加上.

1 if (env.IsDevelopment())
2 {
3     app.UseDeveloperExceptionPage();
4 }
5 else
6 {
7     app.UseExceptionHandler("/Home/Error");
8 }

 

5.自定义Middleare处理

通过middleware全局处理。

复制代码
 1 public class ErrorHandlingMiddleware
 2 {
 3    private readonly RequestDelegate next;
 4 
 5    public ErrorHandlingMiddleware(RequestDelegate next)
 6    {
 7         this.next = next;
 8    }
 9 
10    public async Task Invoke(HttpContext context)
11    {
12         try
13         {
14            await next(context);
15         }
16         catch (System.Exception ex)
17         {
18            //处理异常
19         }
20    }
21 }
复制代码

 如有侵权,请联系作者,将进行整改

posted @   C#初级程序员  阅读(163)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示