本文转自:https://damienbod.com/2015/09/30/asp-net-5-exception-filters-and-resource-filters/

This article shows how an exception filter and a resource filter can be used in ASP.NET Core

Code: https://github.com/damienbod/AspNet5Filters

2017.07.01: Updated to VS2017 and csproj 2016.07.01: Updated to ASP.NET Core 1.0 RTM 2016.05.17: Updated to ASP.NET Core 1.0 RC2 dotnet 2015.11.18: Updated to ASP.NET Core 1.0 RC1 2015.10.16: Updated to ASP.NET Core 1.0 beta8

An exception filter can be implemented using the IExceptionFilterinterface or by implementing the abstract class ExceptionFilter. The ExceptionFilter class implements the IAsyncExceptionFilter, IExceptionFilter and the IOrderedFilter interfaces. In a MVC 6 controller, the ExceptionFilter can be used directly, as a ServiceFilter or as a TypeFilter, on the class itself or applied to single methods. The ExceptionFilter can also be added globally in the Startup class.

A custom resource filter is implemented by using the IResourceFilterinterface. The resource filter method OnResourceExecuting is called before all action filters and exception filters and the resource filter OnResourceExecuted method is called after all action filter and exception filters.

Custom Exception Filter

The following code is an example of a custom filter implemented using the abstract class ExceptionFilterAttribute. The filter does not require a default constructor and can be used to add dependencies which will be added using the MVC 6 IoC.

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging; namespace AspNet5.Filters.ExceptionFilters
{
public class CustomOneLoggingExceptionFilter : ExceptionFilterAttribute
{
private readonly ILogger _logger; public CustomOneLoggingExceptionFilter(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("CustomOneLoggingExceptionFilter");
} public override void OnException(ExceptionContext context)
{
_logger.LogInformation("OnException");
base.OnException(context);
} //public override Task OnExceptionAsync(ExceptionContext context)
//{
// _logger.LogInformation("OnActionExecuting async");
// return base.OnExceptionAsync(context);
//}
}
}

Custom Resource Filter

A custom filter can also be implemented using the IResourceFilter interface.

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging; namespace AspNet5.Filters.ResourceFilters
{
public class CustomOneResourceFilter : IResourceFilter
{ private readonly ILogger _logger; public CustomOneResourceFilter(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("CustomOneResourceFilter");
} public void OnResourceExecuted(ResourceExecutedContext context)
{
_logger.LogInformation("OnResourceExecuted");
} public void OnResourceExecuting(ResourceExecutingContext context)
{
_logger.LogInformation("OnResourceExecuting");
}
}
}

Startup class code configuration

Global filters can be added using the ConfigureServices method in the Startup class. If the custom filters are used as ServiceType filters in the controller classes, the custom filters need to be added to the MVC 6 IoC.

public void ConfigureServices(IServiceCollection services)
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole();
loggerFactory.AddDebug(); services.AddMvc(
config =>
{
config.Filters.Add(new GlobalFilter(loggerFactory));
config.Filters.Add(new GlobalLoggingExceptionFilter(loggerFactory));
}); services.AddScoped<ConsoleLogActionOneFilter>();
services.AddScoped<ConsoleLogActionTwoFilter>();
services.AddScoped<ClassConsoleLogActionBaseFilter>();
services.AddScoped<ClassConsoleLogActionOneFilter>(); services.AddScoped<CustomOneLoggingExceptionFilter>();
services.AddScoped<CustomTwoLoggingExceptionFilter>();
services.AddScoped<CustomOneResourceFilter>();
}

Request with Exception with default filters

The TestExceptionController implements the default exception example.

using System;
using System.Collections.Generic;
using AspNet5.Filters.ActionFilters;
using AspNet5.Filters.ExceptionFilters;
using AspNet5.Filters.ResourceFilters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; namespace AspNet5.Controllers
{
[Route("api/[controller]")]
[ServiceFilter(typeof(CustomTwoLoggingExceptionFilter))]
public class TestExceptionController : Controller
{
private readonly ILogger _logger; public TestExceptionController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("TestExceptionController");
} [HttpGet]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter))]
[ServiceFilter(typeof(CustomOneResourceFilter))]
[ServiceFilter(typeof(ConsoleLogActionTwoFilter))]
public IEnumerable<string> Get()
{
_logger.LogInformation("Executing Http Get before exception");
throw new Exception("Yes a great exception");
} [HttpGet("getwithorder")]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter), Order = -1)]
[ServiceFilter(typeof(CustomOneResourceFilter))]
public IEnumerable<string> GetWithOrderedFiltered()
{
_logger.LogInformation("Executing Http Get before exception");
throw new Exception("Yes a great exception");
} [HttpGet("getcustomexception")]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter))]
[ServiceFilter(typeof(CustomOneResourceFilter))]
public IEnumerable<string> GetWithCustomException()
{
_logger.LogInformation("Executing Http Get before exception");
throw new CustomException("Yes a great exception");
} [HttpGet("getnoexception")]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter))]
[ServiceFilter(typeof(CustomOneResourceFilter))]
public IEnumerable<string> GetNoException()
{
_logger.LogInformation("Executing Http GetNoException");
return new string[] { "test data one", "test data two" };
} }
}

When the HTTP Request is executed in the MVC 6 pipeline, the Resource filters OnResourceExecuting is executed first. Then all the action filter OnResourceExecuting are executed. The method itself is then executed. After this, all the action filter OnResourceExecuted are executed. Then the Exception filters are called. (OnException ). The Resource filter OnResourceExecuted is called at the end.

The result can also be viewed in in the console (start the application in the console with dnx web):

The exception filter closest the the action method is executed first, then the controller class filter, and then the global exception filter. The resource filter is executed at the end.

Request with Exception with handled exception

This example stops executing ExceptionFilters if a CustomException is throw. This is done by setting the Exception property of the ExceptionContext to null. The following OnException methods exception filters are not executed.

public override void OnException(ExceptionContext context)
{
_logger.LogInformation("OnActionExecuting");
handleCustomException(context);
base.OnException(context);
} private void handleCustomException(ExceptionContext context)
{
if (context.Exception.GetType() == typeof(CustomException))
{
_logger.LogInformation("Handling the custom exception here, will not pass it on to further exception filters");
context.Exception = null;
}
}

The example is implemented in the controller as follows:

[HttpGet("getcustomexception")]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter))]
[ServiceFilter(typeof(CustomOneResourceFilter))]
public IEnumerable<string> GetWithCustomException()
{
_logger.LogInformation("Executing Http Get before exception");
throw new CustomException("Yes a great exception");
}

This can be called in a browser with the URL: http://localhost:5000/api/testexception/getcustomexception

The global exception filter is never called.

Request with Exception with handled exception ordered

The Exception filter with the highest Order property value is executed first. We can force that the CustomOneLoggingExceptionFilter is executed last by setting the Order property to -1, less than the default Order value.

[HttpGet("getwithorder")]
[ServiceFilter(typeof(CustomOneLoggingExceptionFilter), Order = -1)]
[ServiceFilter(typeof(CustomOneResourceFilter))]
public IEnumerable<string> GetWithOrderedFiltered()
{
_logger.LogInformation("Executing Http Get before exception");
throw new Exception("Yes a great exception");
}

This can be tested in the browser with the URL: http://localhost:5000/api/testexception/getwithorder

The executed order has been changed:

Links:

https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Abstractions/Filters/IResourceFilter.cs

div{float:left;margin-right:10px;}
div.wpmrec2x div.u > div:nth-child(3n){margin-right:0px;}
-->

Advertisements

 

最新文章

  1. 安卓android sharepreference数据存储,保存输入框里面的数据
  2. nyoj756_重建二叉树_先序遍历
  3. RaisingStudio.SessionFactory 发布 0.1版
  4. ReactJS入门学习二
  5. 控制不能离开Finally子句主体
  6. hdu 1211 RSA
  7. execution 表达式
  8. A Tour of Go Variables
  9. 特殊浮点值 Java
  10. NYOJ17,单调递增最长子序列
  11. Win32 GDI基础(笔记)
  12. [C#基础] 数据类型
  13. SQL_sql的简单查询
  14. tastypie Django REST API developement 1)
  15. Python开篇
  16. Gulp教程之:Gulp能做什么,前端装逼为何要用它
  17. scrapy爬虫之断点续爬和多个spider同时爬取
  18. Ubuntu shutdown now 关机后 开机黑屏
  19. js-ES6学习笔记-let命令
  20. 将目录结构输出为json格式(zTree)

热门文章

  1. VSCode提示pylint isnot installed
  2. python3好用的mysql.connector库
  3. 从map中取出最大或最小value对应的key---多种写法
  4. selenium定位元素提示‘元素不可见’问题解决方法
  5. WinForm中如何实现在容器控件中嵌入form窗体(panel与子窗体)
  6. screen虚拟终端
  7. CentOS 中安装 jdk
  8. asp.net MVC中的@model与Model
  9. Idea 软件Project项目的jar依赖关系设置方法
  10. Java实现连接FTP服务并传递文件