本文旨在:
1 继承ExceptionFilterAttribute,重写Override OnException(ExceptionContext context)处理异常
2 在.netCore中配置属性文件ExceptionFilterAttribute的构造方法注入
现在我们逐步实现以上两个功能:
新建class文件,命名ExceptionHandler,继承特性ExceptionFilterAttribute,重写 OnException,处理异常,这里我封装了ReturnResult方法处理ActionResult
public class ExceptionHandle : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var ex = context.Exception;
var controllername = context.RouteData.Values["controller"].ToString();
var actionname = context.RouteData.Values["action"].ToString();
if (context.ExceptionHandled == false)
{
context.Result= ReturnResult(resultType.ContentResult,ex);
}
context.ExceptionHandled = true; //异常已处理了
}
}
ReturnResult方法代码:这里总结了三种形式的输出1 ContentResult重写请求页面内容输出异常,2 JsonResult Json格式返回异常,3 Redirect页面跳转
private IActionResult ReturnResult(resultType rtype, Exception ex)
{
IActionResult result;
switch (rtype)
{
case resultType.ContentResult:
result = new ContentResult
{
Content = ex.Message,
StatusCode = StatusCodes.Status500InternalServerError,
ContentType = "text/html;charset=utf-8"
};
break;
case resultType.JsonResult:
result = new JsonResult(new { msg = ex.Message });
break;
case resultType.Redirect:
result = new RedirectToRouteResult(
new RouteValueDictionary{
{ "controller","Home"},
{"action","Error" },
{"msg",ex.Message }
}
);
break;
default:
result = new RedirectResult("../home/error");
break;
}
return result;
}
enum resultType
{
ContentResult = 1,
JsonResult = 2,
Redirect = 3
}
2 使用.netCore做依赖注入,这里我们为ExceptionHandle属性文件做注入配置
startup.cs 配置服务:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddScoped<ExceptionHandle>();
}
使用:构造方法根据需要补充参数,.netcore会自动为该传参做注入
public class ExceptionHandle : ExceptionFilterAttribute
{
private readonly ILogger<ExceptionHandle> _logger;
public ExceptionHandle(ILogger<ExceptionHandle> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
_logger.LogError(ex.Message, context.Exception);//调用
}
}
Action调用:ServiceFilter
[ServiceFilter(typeof(ExceptionHandle))]
public IActionResult Index(DateTime dt, long sjc)
{
var chushu = 0;
var i = 1 / chushu;
return View()
}
总结:定义继承自ExceptionFilterAttribute属性类的Filter文件类,重写OnException方法,如果不需要在属性类中使用其他服务当日也无需做注入,调用在Action上一行写上[AttributeName]即可
//[ServiceFilter(typeof(ExceptionHandle))]
[ExceptionHandle]
public IActionResult Index(DateTime dt, long sjc)
{
var chushu = 0;
var i = 1 / chushu;
return View()
}
本文来自博客园,作者:jiayouliucui,转载请注明原文链接:https://www.cnblogs.com/cheery-go/p/15627337.html