FriendlyExceptionServiceCollectionExtensions.cs
3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using NCC.Dependency;
using NCC.FriendlyException;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 友好异常服务拓展类
/// </summary>
[SuppressSniffer]
public static class FriendlyExceptionServiceCollectionExtensions
{
/// <summary>
/// 添加友好异常服务拓展服务
/// </summary>
/// <typeparam name="TErrorCodeTypeProvider">异常错误码提供器</typeparam>
/// <param name="mvcBuilder">Mvc构建器</param>
/// <param name="configure">是否启用全局异常过滤器</param>
/// <returns></returns>
public static IMvcBuilder AddFriendlyException<TErrorCodeTypeProvider>(this IMvcBuilder mvcBuilder, Action<FriendlyExceptionServiceOptions> configure = null)
where TErrorCodeTypeProvider : class, IErrorCodeTypeProvider
{
mvcBuilder.Services.AddFriendlyException<TErrorCodeTypeProvider>(configure);
return mvcBuilder;
}
/// <summary>
/// 添加友好异常服务拓展服务
/// </summary>
/// <typeparam name="TErrorCodeTypeProvider">异常错误码提供器</typeparam>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection AddFriendlyException<TErrorCodeTypeProvider>(this IServiceCollection services, Action<FriendlyExceptionServiceOptions> configure = null)
where TErrorCodeTypeProvider : class, IErrorCodeTypeProvider
{
// 添加全局异常过滤器
services.AddFriendlyException(configure);
// 单例注册异常状态码提供器
services.AddSingleton<IErrorCodeTypeProvider, TErrorCodeTypeProvider>();
return services;
}
/// <summary>
/// 添加友好异常服务拓展服务
/// </summary>
/// <param name="mvcBuilder">Mvc构建器</param>
/// <param name="configure"></param>
/// <returns></returns>
public static IMvcBuilder AddFriendlyException(this IMvcBuilder mvcBuilder, Action<FriendlyExceptionServiceOptions> configure = null)
{
mvcBuilder.Services.AddFriendlyException(configure);
return mvcBuilder;
}
/// <summary>
/// 添加友好异常服务拓展服务
/// </summary>
/// <param name="services"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IServiceCollection AddFriendlyException(this IServiceCollection services, Action<FriendlyExceptionServiceOptions> configure = null)
{
// 添加友好异常配置文件支持
services.AddConfigurableOptions<FriendlyExceptionSettingsOptions>();
// 添加异常配置文件支持
services.AddConfigurableOptions<ErrorCodeMessageSettingsOptions>();
// 载入服务配置选项
var configureOptions = new FriendlyExceptionServiceOptions();
configure?.Invoke(configureOptions);
// 添加全局异常过滤器
if (configureOptions.EnabledGlobalFriendlyException)
services.AddMvcFilter<FriendlyExceptionFilter>();
return services;
}
}
}