.Net Core中使用ExceptionFilter过滤器的方法

所属分类: 网络编程 / ASP.NET 阅读数: 658
收藏 0 赞 0 分享

.Net Core中有各种Filter,分别是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。可以把他们看作是.Net Core自带的AOP的扩展封装。

今天来看其中的一种:ExceptionFilter(用于全局的异常处理)

首先新建一个.Net Core MVC的项目

新建一个控制器:

这里我们可以看到代码运行到16行时会报一个索引项超出集合范围的错误

按照常规的思维我们在代码中会加异常处理,如下:

try
  {
    var range = Enumerable.Range(1, 3).ToArray();
    var result = range[4];

    return View();
  }
  catch (Exception ex)
  {
    throw new Exception(ex.Message);
  }

但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了

上代码:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ExceptionFilter.Filter
{
  public class CustomerExceptionFilter : Attribute, IExceptionFilter
  {
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly IModelMetadataProvider _modelMetadataProvider;

    public CustomerExceptionFilter(IHostingEnvironment hostingEnvironment,
      IModelMetadataProvider modelMetadataProvider)
    {
      _hostingEnvironment = hostingEnvironment;
      _modelMetadataProvider = modelMetadataProvider;
    }
    /// <summary>
    /// 发生异常进入
    /// </summary>
    /// <param name="context"></param>
    public async void OnException(ExceptionContext context)
    {
      if (!context.ExceptionHandled)//如果异常没有处理
      {
        if (_hostingEnvironment.IsDevelopment())//如果是开发环境
        {
          var result = new ViewResult { ViewName = "../Handle/Index" };
          result.ViewData = new ViewDataDictionary(_modelMetadataProvider,
                                context.ModelState);
          result.ViewData.Add("Exception", context.Exception);//传递数据
          context.Result = result;
        }
        else
        {
          context.Result = new JsonResult(new
          {
            Result = false,
            Code = 500,
            Message = context.Exception.Message
          });
        }
        context.ExceptionHandled = true;//异常已处理
      }
    }
  }
}

我们在方法中先以特性来使用,加上这句代码:

[TypeFilter(typeof(CustomerExceptionFilter))]

之后会跳到这个视图:../Handle/Index ,会将异常信息传入到此视图

视图页代码:

<p>Message:@ViewData["Exception"]</p>

(可以自行封装。。。)

我们还可以定义成全局的

在Startup类中的ConfigureServices方法中加入这句代码

services.AddControllersWithViews(option =>
 {
   option.Filters.Add<CustomerExceptionFilter>();
 });
//3.0以下的版本好像应该这样写:services.AddMvc();
更多精彩内容其他人还在看

解析WPF实现音频文件循环顺序播放的解决方法

本篇文章是对WPF实现音频文件循环顺序播放的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决.net framework 4.0环境下遇到版本不同编译不通过的方法详解

本篇文章是对.net framework 4.0环境下遇到版本不同编译不通过的解决方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

将文件上传、下载(以二进制流保存到数据库)实现代码

将文件以二进制流的格式写入数据库:首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中具体请祥看本文,希望对你有所帮助
收藏 0 赞 0 分享

点击提交按钮后DropDownList的值变为默认值实现分析

在点击提交按钮后,页面上所有的绑定到数据库的控件值都恢复到默认值,下面与大家分享下DropDownList的值变为默认值
收藏 0 赞 0 分享

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

Linkbutton控件在项目中的简单应用

Button控件可分为button控件、LinkButton控件、ImageButton控件三类,而LinkButton控件则在页面上显示为一个超级链接,下面与大家分享下其具体应用
收藏 0 赞 0 分享

Web.config 和 App.config 的区别分析

Web.config 和 App.config 的区别分析,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于.Net中的数字与日期格式化规则助记词的使用详解

本篇文章是对.Net中的数字与日期格式化规则助记词的使用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决在Web.config或App.config中添加自定义配置的方法详解

本篇文章是对在Web.config或App.config中添加自定义配置的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入本机影像生成器(Ngen.exe)工具使用方法详解

本篇文章是对本机影像生成器(Ngen.exe)工具使用方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多