.Net Core中有各种Filter,分别是AuthorizationFilter、ResourceFilter、ExceptionFilter、ActionFilter、ResultFilter。可以把他们看作是.Net Core自带的AOP的扩展封装。 今天来看其中的一种:ExceptionFilter(用于全局的异常处理) 首先新建一个.Net Core MVC的项目 新建一个控制器:

    .Net Core--ExceptionFilter - 图1

    这里我们可以看到代码运行到16行时会报一个索引项超出集合范围的错误 按照常规的思维我们在代码中会加异常处理,如下:
    1. try
    2. {
    3. var range = Enumerable.Range(1, 3).ToArray();
    4. var result = range[4];
    5. return View();
    6. }
    7. catch (Exception ex)
    8. {
    9. throw new Exception(ex.Message);
    10. }
    但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了 上代码:

    .Net Core--ExceptionFilter - 图2

    1. using Microsoft.AspNetCore.Hosting;
    2. using Microsoft.AspNetCore.Mvc;
    3. using Microsoft.AspNetCore.Mvc.Filters;
    4. using Microsoft.AspNetCore.Mvc.ModelBinding;
    5. using Microsoft.AspNetCore.Mvc.ViewFeatures;
    6. using System;
    7. using System.Collections.Generic;
    8. using System.Linq;
    9. using System.Threading.Tasks;
    10. namespace ExceptionFilter.Filter
    11. {
    12. public class CustomerExceptionFilter : Attribute, IExceptionFilter
    13. {
    14. private readonly IHostingEnvironment _hostingEnvironment;
    15. private readonly IModelMetadataProvider _modelMetadataProvider;
    16. public CustomerExceptionFilter(IHostingEnvironment hostingEnvironment,
    17. IModelMetadataProvider modelMetadataProvider)
    18. {
    19. _hostingEnvironment = hostingEnvironment;
    20. _modelMetadataProvider = modelMetadataProvider;
    21. }
    22. /// <summary>
    23. /// 发生异常进入
    24. /// </summary>
    25. /// <param name="context"></param>
    26. public async void OnException(ExceptionContext context)
    27. {
    28. if (!context.ExceptionHandled)//如果异常没有处理
    29. {
    30. if (_hostingEnvironment.IsDevelopment())//如果是开发环境
    31. {
    32. var result = new ViewResult { ViewName = "../Handle/Index" };
    33. result.ViewData = new ViewDataDictionary(_modelMetadataProvider,
    34. context.ModelState);
    35. result.ViewData.Add("Exception", context.Exception);//传递数据
    36. context.Result = result;
    37. }
    38. else
    39. {
    40. context.Result = new JsonResult(new
    41. {
    42. Result = false,
    43. Code = 500,
    44. Message = context.Exception.Message
    45. });
    46. }
    47. context.ExceptionHandled = true;//异常已处理
    48. }
    49. }
    50. }
    51. }
    我们在方法中先以特性来使用,加上这句代码:

    <font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">[TypeFilter(</font><font style="color:rgb(0, 0, 255);background-color:rgb(242, 244, 245);">typeof</font><font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">(CustomerExceptionFilter))]</font>

    .Net Core--ExceptionFilter - 图3

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

    <font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);"> <p>Message:@ViewData[</font><font style="color:rgb(128, 0, 0);background-color:rgb(242, 244, 245);">"Exception"</font><font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">]</p></font>

    (可以自行封装。。。) 我们还可以定义成全局的,在Startup类中的ConfigureServices方法中加入这句代码
    1. services.AddControllersWithViews(option =>
    2. {
    3. option.Filters.Add<CustomerExceptionFilter>();
    4. });
    5. //3.0以下的版本好像应该这样写:services.AddMvc();

    关于AddMvc/AddMvcCore/AddControllers等区别,移步:https://www.yuque.com/schafferyy/net/twgia8