فهرست منبع

😁代码调整及优化

zuohuaijun 2 سال پیش
والد
کامیت
b4f4379f36

+ 5 - 7
Admin.NET/Admin.NET.Application/Configuration/Cache.json

@@ -10,7 +10,7 @@
     }
   },
   "Cluster": { // 集群配置
-    "Enabled": true, // 启用集群:Cache.json使用Redis方式,OSS.json不能使用本地方式保存文件
+    "Enabled": false, // 启用集群:前提开启Redis缓存模式
     "ServerId": "adminnet", // 服务器标识
     "ServerIp": "", // 服务器IP
     "SignalR": {
@@ -18,17 +18,15 @@
       "ChannelPrefix": "signalrPrefix_"
     }
   },
-  "StackExchangeRedis": {
+  "StackExchangeRedis": { // 数据保护
     "DefaultDb": "4",
     "EndPoints": [
-      "10.10.0.123:26379",// 哨兵端口
-      "10.10.0.124:26380",
-      "10.10.0.125:26381"
+      // "10.10.0.124:26380", // 哨兵端口
     ],
     "MainPrefix": "adminNet:",
     "Password": "123456",
-    "SentinelPassword": "1qaz",
-    "ServiceName": "mymaster",
+    "SentinelPassword": "adminNet",
+    "ServiceName": "adminNet",
     "SignalRChannelPrefix": "signalR:"
   }
 }

+ 2 - 1
Admin.NET/Admin.NET.Core/Admin.NET.Core.csproj

@@ -31,6 +31,7 @@
     <PackageReference Include="Magicodes.IE.Pdf" Version="2.7.4.5" />
     <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.23" />
     <PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="6.0.23" />
+    <PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="6.0.23" />
     <PackageReference Include="NEST" Version="7.17.5" />
     <PackageReference Include="NewLife.Redis" Version="5.5.2023.1001" />
     <PackageReference Include="OnceMi.AspNetCore.OSS" Version="1.1.9" />
@@ -40,7 +41,7 @@
     <PackageReference Include="System.Linq.Dynamic.Core" Version="1.3.5" />
     <PackageReference Include="UAParser" Version="3.1.47" />
     <PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
-    <PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.20" />
+    <PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.23" />
   </ItemGroup>
 
   <ItemGroup>

+ 48 - 0
Admin.NET/Admin.NET.Core/OAuth/OAuthSetup.cs

@@ -0,0 +1,48 @@
+// 麻省理工学院许可证
+//
+// 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司  联系电话/微信:18020030720  QQ:515096995
+//
+// 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
+//
+// 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
+// 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
+
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+
+namespace Admin.NET.Core;
+
+public static class OAuthSetup
+{
+    /// <summary>
+    /// 三方授权登录OAuth注册
+    /// </summary>
+    /// <param name="services"></param>
+    public static void AddOAuth(this IServiceCollection services)
+    {
+        var authOpt = App.GetOptions<OAuthOptions>();
+        services.AddAuthentication(options =>
+            {
+                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
+                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+            })
+            .AddCookie(options =>
+            {
+                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
+                options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
+            })
+            .AddWeixin(options =>
+            {
+                options.ClientId = authOpt.Weixin?.ClientId;
+                options.ClientSecret = authOpt.Weixin?.ClientSecret;
+            })
+            .AddGitee(options =>
+            {
+                options.ClientId = authOpt.Gitee?.ClientId;
+                options.ClientSecret = authOpt.Gitee?.ClientSecret;
+
+                options.ClaimActions.MapJsonKey(OAuthClaim.GiteeAvatarUrl, "avatar_url");
+            });
+    }
+}

+ 5 - 2
Admin.NET/Admin.NET.Core/Option/StackExchangeRedisOptions.cs

@@ -21,10 +21,13 @@ public sealed class StackExchangeRedisOptions : IConfigurableOptions
     public string SentinelPassword { get; set; }
 
     /// <summary>
-    /// 
+    /// 哨兵端口
     /// </summary>
     public List<string> EndPoints { get; set; }
 
+    /// <summary>
+    /// 默认库
+    /// </summary>
     public int DefaultDb { get; set; }
 
     /// <summary>
@@ -33,7 +36,7 @@ public sealed class StackExchangeRedisOptions : IConfigurableOptions
     public string MainPrefix { get; set; }
 
     /// <summary>
-    ///  SignalR 前缀
+    /// SignalR前缀
     /// </summary>
     public string SignalRChannelPrefix { get; set; }
 }

+ 90 - 0
Admin.NET/Admin.NET.Core/SignalR/SignalRSetup.cs

@@ -0,0 +1,90 @@
+// 麻省理工学院许可证
+//
+// 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司  联系电话/微信:18020030720  QQ:515096995
+//
+// 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
+//
+// 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
+// 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
+
+using Furion.Logging.Extensions;
+using Microsoft.AspNetCore.DataProtection;
+using StackExchange.Redis;
+
+namespace Admin.NET.Core;
+
+public static class SignalRSetup
+{
+    /// <summary>
+    /// 即时消息SignalR注册
+    /// </summary>
+    /// <param name="services"></param>
+    /// <param name="SetNewtonsoftJsonSetting"></param>
+    public static void AddSignalR(this IServiceCollection services, Action<JsonSerializerSettings> SetNewtonsoftJsonSetting)
+    {
+        var signalRBuilder = services.AddSignalR(options =>
+        {
+            options.EnableDetailedErrors = true;
+            options.ClientTimeoutInterval = TimeSpan.FromMinutes(2);
+            options.KeepAliveInterval = TimeSpan.FromMinutes(1);
+        }).AddNewtonsoftJsonProtocol(options => SetNewtonsoftJsonSetting(options.PayloadSerializerSettings));
+
+        // 若未启用Redis缓存,直接返回
+        var cacheOptions = App.GetOptions<CacheOptions>();
+        if (cacheOptions.CacheType != CacheTypeEnum.Redis.ToString())
+            return;
+
+        // 若已开启集群配置,则把SignalR配置为支持集群模式
+        var clusterOpt = App.GetOptions<ClusterOptions>();
+        if (clusterOpt.Enabled)
+        {
+            // StackExchangeRedis 缓存
+            var redisOptions = App.GetOptions<StackExchangeRedisOptions>();
+
+            // 密钥存储(数据保护)
+            var redisConfig = new ConfigurationOptions
+            {
+                AbortOnConnectFail = false,
+                ServiceName = redisOptions.ServiceName,
+                AllowAdmin = true,
+                DefaultDatabase = redisOptions.DefaultDb,
+                Password = redisOptions.Password
+            };
+            redisOptions.EndPoints.ForEach(o => redisConfig.EndPoints.Add(o));
+            var connection1 = ConnectionMultiplexer.Connect(redisConfig);
+            services.AddDataProtection().PersistKeysToStackExchangeRedis(connection1, "AdminNet:DataProtection-Keys");
+
+            signalRBuilder.AddStackExchangeRedis(clusterOpt.SignalR.RedisConfiguration, options =>
+            {
+                // 此处设置的ChannelPrefix并不会生效,如果两个不同的项目,且[程序集名+类名]一样,使用同一个redis服务,请注意修改 Hub/OnlineUserHub 的类名。
+                // 原因请参考下边链接:
+                // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs#L74
+                // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/Internal/RedisChannels.cs#L33
+                options.Configuration.ChannelPrefix = clusterOpt.SignalR.ChannelPrefix;
+                options.ConnectionFactory = async writer =>
+                {
+                    var config = new ConfigurationOptions
+                    {
+                        AbortOnConnectFail = false,
+                        ServiceName = redisOptions.ServiceName,
+                        AllowAdmin = true,
+                        DefaultDatabase = redisOptions.DefaultDb,
+                        Password = redisOptions.Password
+                    };
+                    redisOptions.EndPoints.ForEach(o => config.EndPoints.Add(o));
+                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
+                    connection.ConnectionFailed += (_, e) =>
+                    {
+                        "连接 Redis 失败".LogError();
+                    };
+
+                    if (!connection.IsConnected)
+                    {
+                        "无法连接 Redis".LogError();
+                    }
+                    return connection;
+                };
+            });
+        }
+    }
+}

+ 0 - 1
Admin.NET/Admin.NET.Web.Core/Admin.NET.Web.Core.csproj

@@ -13,7 +13,6 @@
 
   <ItemGroup>
     <PackageReference Include="IGeekFan.AspNetCore.Knife4jUI" Version="0.0.16" />
-    <PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="6.0.23" />
     <PackageReference Include="System.Security.Cryptography.Pkcs" Version="7.0.3" />
   </ItemGroup>
 

+ 3 - 3
Admin.NET/Admin.NET.Web.Core/ProjectOptions.cs

@@ -27,6 +27,7 @@ public static class ProjectOptions
         services.AddConfigurableOptions<SnowIdOptions>();
         services.AddConfigurableOptions<CacheOptions>();
         services.AddConfigurableOptions<ClusterOptions>();
+        services.AddConfigurableOptions<StackExchangeRedisOptions>();
         services.AddConfigurableOptions<OSSProviderOptions>();
         services.AddConfigurableOptions<UploadOptions>();
         services.AddConfigurableOptions<WechatOptions>();
@@ -38,7 +39,7 @@ public static class ProjectOptions
         services.AddConfigurableOptions<EmailOptions>();
         services.AddConfigurableOptions<OAuthOptions>();
         services.AddConfigurableOptions<CryptogramOptions>();
-        services.AddConfigurableOptions<SMSOptions>();
+        services.AddConfigurableOptions<SMSOptions>();        
         //services.AddConfigurableOptions<IpRateLimitingOptions>();
         //services.AddConfigurableOptions<IpRateLimitPoliciesOptions>();
         //services.AddConfigurableOptions<ClientRateLimitingOptions>();
@@ -47,8 +48,7 @@ public static class ProjectOptions
         services.Configure<IpRateLimitPolicies>(App.Configuration.GetSection("IpRateLimitPolicies"));
         services.Configure<ClientRateLimitOptions>(App.Configuration.GetSection("ClientRateLimiting"));
         services.Configure<ClientRateLimitPolicies>(App.Configuration.GetSection("ClientRateLimitPolicies"));
-        services.AddConfigurableOptions<StackExchangeRedisOptions>();
-
+     
         return services;
     }
 }

+ 3 - 91
Admin.NET/Admin.NET.Web.Core/Startup.cs

@@ -14,9 +14,6 @@ using Furion;
 using Furion.SpecificationDocument;
 using Furion.VirtualFileServer;
 using IGeekFan.AspNetCore.Knife4jUI;
-using Microsoft.AspNetCore.Authentication;
-using Microsoft.AspNetCore.Authentication.Cookies;
-using Microsoft.AspNetCore.Authentication.JwtBearer;
 using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.HttpOverrides;
@@ -24,13 +21,9 @@ using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Newtonsoft.Json;
 using OnceMi.AspNetCore.OSS;
-using StackExchange.Redis;
 using System;
 using System.Net;
 using System.Net.Mail;
-using Microsoft.AspNetCore.DataProtection;
-using Furion.Logging.Extensions;
-using Microsoft.AspNetCore.SignalR;
 
 namespace Admin.NET.Web.Core;
 
@@ -83,30 +76,8 @@ public class Startup : AppStartup
             //.AddXmlDataContractSerializerFormatters()
             .AddInjectWithUnifyResult<AdminResultProvider>();
 
-        // 第三方授权登录
-        var authOpt = App.GetOptions<OAuthOptions>();
-        services.AddAuthentication(options =>
-            {
-                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
-                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
-            })
-            .AddCookie(options =>
-            {
-                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
-                options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
-            })
-            .AddWeixin(options =>
-            {
-                options.ClientId = authOpt.Weixin?.ClientId;
-                options.ClientSecret = authOpt.Weixin?.ClientSecret;
-            })
-            .AddGitee(options =>
-            {
-                options.ClientId = authOpt.Gitee?.ClientId;
-                options.ClientSecret = authOpt.Gitee?.ClientSecret;
-
-                options.ClaimActions.MapJsonKey(OAuthClaim.GiteeAvatarUrl, "avatar_url");
-            });
+        // 三方授权登录OAuth
+        services.AddOAuth();
 
         // ElasticSearch
         services.AddElasticSearch();
@@ -160,66 +131,7 @@ public class Startup : AppStartup
         services.AddViewEngine();
 
         // 即时通讯
-        var signalRBuilder = services.AddSignalR(options =>
-        {
-            options.EnableDetailedErrors = true;
-            options.ClientTimeoutInterval = TimeSpan.FromMinutes(2);
-            options.KeepAliveInterval = TimeSpan.FromMinutes(1);
-        }).AddNewtonsoftJsonProtocol(options => SetNewtonsoftJsonSetting(options.PayloadSerializerSettings));
-
-        // 若已开启集群配置,则把SignalR配置为支持集群模式
-        var clusterOpt = App.GetOptions<ClusterOptions>();
-        if (clusterOpt.Enabled)
-        {
-            // StackExchangeRedis 缓存
-            var redisOptions = App.GetOptions<StackExchangeRedisOptions>();
-
-            // 密钥存储(数据保护)
-            var redisConfig = new ConfigurationOptions
-            {
-                AbortOnConnectFail = false,
-                ServiceName = redisOptions.ServiceName,
-                AllowAdmin = true,
-                DefaultDatabase = redisOptions.DefaultDb,
-                Password = redisOptions.Password
-            };
-            redisOptions.EndPoints.ForEach(o => redisConfig.EndPoints.Add(o));
-            var connection1 = ConnectionMultiplexer.Connect(redisConfig);
-            services.AddDataProtection()
-                .PersistKeysToStackExchangeRedis(connection1, "AdminNet:DataProtection-Keys");
-
-            signalRBuilder.AddStackExchangeRedis(clusterOpt.SignalR.RedisConfiguration, options =>
-                {
-                    // 此处设置的ChannelPrefix并不会生效,如果两个不同的项目,且[程序集名+类名]一样,使用同一个redis服务,请注意修改 Hub/OnlineUserHub 的类名。
-                    // 原因请参考下边链接:
-                    // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs#L74
-                    // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/Internal/RedisChannels.cs#L33
-                    options.Configuration.ChannelPrefix = clusterOpt.SignalR.ChannelPrefix;
-                    options.ConnectionFactory = async writer =>
-                    {
-                        var config = new ConfigurationOptions
-                        {
-                            AbortOnConnectFail = false,
-                            ServiceName = redisOptions.ServiceName,
-                            AllowAdmin = true,
-                            DefaultDatabase = redisOptions.DefaultDb,
-                            Password = redisOptions.Password
-                        };
-                        redisOptions.EndPoints.ForEach(o => config.EndPoints.Add(o));
-                        var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
-                        connection.ConnectionFailed += (_, e) =>
-                        {
-                            "Connection to Redis failed.".LogError();
-                        };
-
-                        if (!connection.IsConnected)
-                        {
-                            "Did not connect to Redis.".LogError();
-                        }
-                        return connection;
-                    };
-                });
-        }
+        services.AddSignalR(SetNewtonsoftJsonSetting);
 
         // 系统日志
         services.AddLoggingSetup();