1.继承Controller,重写OnActionExecuted
默认都会继承⼀个Controller类,重写OnActionExecuted,添加上异常处理即可。⼀般情况下我们会新建
⼀个BaseController, 让所有Controller继承BaseController。代码如下
1
public class BaseController : Controller
2
{
57
3
public override void OnActionExecuted(ActionExecutedContext c
ontext)
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.Messa
ge }"
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 c
ontext)
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);
58
15
}
16
17
public override void OnResultExecuted(ResultExecutedContext c
ontext)
18
{
19
var exception = context.Exception;
20
if (exception != null)
21
{
22
context.ExceptionHandled = true;
23
context.HttpContext.Response.WriteAsync($"
错误
: {exce
ption.Message}");
24
}
25
base.OnResultExecuted(context);
26
}
27
}
使⽤⽅式有两种,
在controller⾥打上 [TypeFilter(typeof(ExceptionActionFilter)] 标签;
在Startup⾥以filter⽅式全局注⼊。
1
services.AddControllersWithViews(options =>
2
{
3
options.Filters.Add<ExceptionActionFilterAttribute>();
4
})
3.使⽤ IExceptionFilter
我们知道, Asp.Net Core提供了5类filter, IExceptionFilter是其中之⼀,顾名思义,这就是⽤来处理异常
的。Asp.net Core中ExceptionFilterAttribute已经实现了IExceptionFilter,所以我们只需继承
ExceptionFilterAttribute,重写其中⽅法即可。 同样新建CustomExceptionFilterAttribute继承
ExceptionFilterAttribute,重写 OnException ,添加异常处理,完整代码如下:
1
public class CustomExceptionFilterAttribute : ExceptionFilterAttri
bute
2
{
3
public override void OnException(ExceptionContext context)
4
{
59
5
context.ExceptionHandled = true;
6
context.HttpContext.Response.WriteAsync($"CustomExceptionF
ilterAttribute
错误
:{context.Exception.Message}");
7
base.OnException(context);
8
}
9
}
4.使⽤ExceptionHandler.
在 startup ⾥,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
{
60
14
await next(context);
15
}
16
catch (System.Exception ex)
17
{
18
//
处理异常
19
}
20
}
21
}