.Net Core 拦截器简单理解

1.拦截器的使用场景

  场景1: 报错异常机制的处理. 创建一个类继承ExceptionFilterAttribute

  场景2: 写WebAPI

  场景3: 类前面可以使用,方法前面也可以使用.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Asp.NetCore.CommTool
{
/// <summary>
/// 异常报错自定义拦截器
/// </summary>
public class CustomExceptionFilter:ExceptionFilterAttribute
{
private readonly ILogger<CustomExceptionFilter> _logger;

private readonly IModelMetadataProvider _modelMetadataProvider;
public CustomExceptionFilter(ILogger<CustomExceptionFilter> logger, IModelMetadataProvider modelMetadataProvider)
{
_logger = logger;
_modelMetadataProvider = modelMetadataProvider;
}
//1.继承这个特性ExceptionFilterAttribute
//2.重写这个方法.
public override void OnException(ExceptionContext context)
{
//有用信息
//报错信息:context.Exception.Message;
//报错方法:context.ActionDescriptor.DisplayName;
//获取或设置一个值,该值指示是否已处理异常。
//写入日志!!!!!!!!!!!!!!Log4
if (!context.ExceptionHandled)
{
//中断式.直接返给界面.
context.Result = new JsonResult(new {retuslt=false,msg= context.Exception.Message});
}
context.ExceptionHandled = true; //告诉系统,这个异常已经处理了,不用再处理
base.OnException(context);
}
}
}

----------------------------------------使用方式--------------------------------------

//异常拦截器 方式1:直接暴露给界面
//[CustomExceptionFilter]
//异常拦截器 方式2:可以保存到日志  
[TypeFilter(typeof(CustomExceptionFilter))]
public IActionResult Index()
{
  //可以直接读第一层的文本值
  //string logging = this._configuration["AllowedHosts"];
  //读更深层次的值
  //string logging0 = this._configuration["Logging:LogLevel:Default"];
  //乱码问题.点击进去appsettings.json更改保存格式的编码为utf-8,重新保存.
  string logging0 = this._configuration["B:C:0"];
  string logging1 = this._configuration["B:C:9"].ToString();
  return View();
}

原文地址:https://www.cnblogs.com/TanYong/p/14329558.html