zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
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
using Prow.Web.SignalR;
using Microsoft.AspNetCore.SignalR;
#if NETSTANDARD2_0
using Newtonsoft.Json.Serialization;
#endif
using System;
using System.Threading.Tasks;
 
namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// SignalR 异常过滤器扩展方法
    /// </summary>
    public static class SignalRExceptionFilterExtensions
    {
#if NETSTANDARD2_0
        /// <summary>
        /// AddJsonProtocal 方法 内部设置序列化规则 时间类型格式字符串为 "yyyy-MM-dd HH:mm:ss"
        /// </summary>
        /// <param name="builder">ISignalRServerBuilder 实例</param>
        /// <returns></returns>
        public static ISignalRServerBuilder AddJsonProtocalDefault(this ISignalRServerBuilder builder)
        {
            return builder.AddJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver();
                options.PayloadSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
        }
#endif
 
        /// <summary>
        /// SignalR Exception Filter 注入方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="services">IServiceCollection 实例</param>
        /// <param name="handler">异常处理回调函数</param>
        /// <returns></returns>
        public static IServiceCollection AddSignalRExceptionFilterHandler<T>(this IServiceCollection services, Func<IHubContext<T>, Exception, Task> handler)
            where T : Hub
        {
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            services.AddSingleton<ISignalRExceptionFilterHandler<T>>(new SignalRExceptionFilterHandler<T>(handler));
            return services;
        }
    }
}