Program.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using Hangfire;
  2. using Hangfire.Redis.StackExchange;
  3. using Microsoft.AspNetCore.Authentication.JwtBearer;
  4. using Microsoft.Extensions.DependencyInjection.Extensions;
  5. using Microsoft.IdentityModel.Tokens;
  6. using System.IdentityModel.Tokens.Jwt;
  7. using TEAMModelOS.SDK.DI;
  8. using TEAMModelOS.SDK;
  9. using HTEX.Complex.Services;
  10. using HTEX.Complex.Services.MQTT;
  11. using MathNet.Numerics;
  12. using MQTTnet.AspNetCore;
  13. using MQTTnet.Server;
  14. using Microsoft.Extensions.Options;
  15. using System.Threading;
  16. using Microsoft.Extensions.Logging;
  17. using System.Text.Json;
  18. using Microsoft.Extensions.Hosting;
  19. using MQTTnet.AspNetCore.Routing;
  20. using Microsoft.AspNetCore.Builder;
  21. using Microsoft.AspNetCore.Hosting.Server;
  22. using Microsoft.AspNetCore.Hosting.Server.Features;
  23. using System.Security.Policy;
  24. using System.Net.Http;
  25. using TEAMModelOS.SDK.DI.Device;
  26. using Serilog;
  27. namespace HTEX.Complex
  28. {
  29. public class Program
  30. {
  31. public static void Main(string[] args)
  32. {
  33. var builder = WebApplication.CreateBuilder(args);
  34. //防止编译后的appsettings.json 文件内容,在重新部署的时候,因为不同的环境导致被覆盖的问题,
  35. //所以在正式环境中指定appsettings-prod.json一个本地开发环境不存在的文件,以达到不会被覆盖的问题,
  36. //即使在生产环境中未配置appsettings-prod.json 也不影响启动,因为会按照appsettings.json的配置启动
  37. #if !DEBUG
  38. builder.Host.ConfigureAppConfiguration((context, config) => {
  39. config.SetBasePath(Directory.GetCurrentDirectory());
  40. config.AddJsonFile("appsettings-prod.json", optional: true, reloadOnChange: true);
  41. });
  42. #endif
  43. Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss.fff zzz} [{Level:u3}] ({ThreadId}) {Message}{NewLine}{Exception}")
  44. .WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day).CreateLogger();
  45. builder.Host.UseSerilog();
  46. //builder.WebHost.ConfigureKestrel(options =>
  47. //{
  48. // //options.ListenAnyIP(4001, options => {
  49. // // // options.UseHttps("Crt/iteden.pfx", "iteden");
  50. // //});
  51. // options.ListenAnyIP(1883, options => { options.UseMqtt();/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
  52. // options.ListenAnyIP(1884, options => { options.UseMqtt();/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
  53. //});
  54. //builder.WebHost.ConfigureKestrel(options =>
  55. //{
  56. // //options.ListenAnyIP(4001, options => {
  57. // // // options.UseHttps("Crt/iteden.pfx", "iteden");
  58. // //});
  59. // options.ListenAnyIP(1883, options => { options.UseMqtt();/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
  60. // options.ListenAnyIP(1884, options => { options.UseMqtt();/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
  61. //});
  62. // Add services to the container.
  63. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  64. builder.Services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  65. .AddJwtBearer(options => //AzureADJwtBearer
  66. {
  67. //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
  68. options.Authority ="https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0";// builder.Configuration["Option:Authority"];
  69. options.Audience = "72643704-b2e7-4b26-b881-bd5865e7a7a5";//builder.Configuration["Option:Audience"];
  70. options.RequireHttpsMetadata = true;
  71. options.TokenValidationParameters = new TokenValidationParameters
  72. {
  73. RoleClaimType = "roles",
  74. //ValidAudiences = new string[] { builder.Configuration["Option:Audience"], $"api://{builder.Configuration["Option:Audience"]}" }
  75. ValidAudiences = new string[] { "72643704-b2e7-4b26-b881-bd5865e7a7a5", $"api://72643704-b2e7-4b26-b881-bd5865e7a7a5" }
  76. };
  77. options.Events = new JwtBearerEvents();
  78. //下列事件有需要紀錄則打開
  79. //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
  80. //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
  81. //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
  82. //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
  83. options.Events.OnTokenValidated = async context =>
  84. {
  85. if (!context.Principal.Claims.Any(x => x.Type.Equals("http://schemas.microsoft.com/identity/claims/scope")) //ClaimConstants.Scope
  86. && !context.Principal.Claims.Any(y => y.Type.Equals("roles"))) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
  87. {
  88. //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
  89. throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
  90. }
  91. await Task.FromResult(0);
  92. };
  93. });
  94. builder.Services.AddControllers();
  95. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  96. builder.Services.AddEndpointsApiExplorer();
  97. //builder.Services.AddSwaggerGen();
  98. builder.Services.AddHttpClient();
  99. string? StorageConnectionString = builder.Configuration.GetValue<string>("Azure:Storage:ConnectionString");
  100. string? RedisConnectionString = builder.Configuration.GetValue<string>("Azure:Redis:ConnectionString");
  101. //Storage
  102. builder.Services.AddAzureStorage(StorageConnectionString, "Default");
  103. //Redis
  104. builder.Services.AddAzureRedis(RedisConnectionString, "Default");
  105. builder.Services.AddSignalR();
  106. builder.Services.AddHttpContextAccessor();
  107. builder.Services.AddHttpClient<DingDing>();
  108. string path = $"{builder.Environment.ContentRootPath}/JsonFiles";
  109. builder.Services.TryAddSingleton(new Region2LongitudeLatitudeTranslator(path));
  110. builder.Services.AddIPSearcher(path);
  111. builder.Services.AddSingleton<CoreDevice>();
  112. builder.Services.AddCors(options =>
  113. {
  114. options.AddDefaultPolicy(
  115. builder =>
  116. {
  117. builder.AllowAnyOrigin()
  118. .AllowAnyHeader()
  119. .AllowAnyMethod();
  120. });
  121. });
  122. builder.Services.AddControllersWithViews();
  123. //MQTT 服务端API 发送消息到MQTT客户端 https://www.cnblogs.com/weskynet/p/16441219.html
  124. #region MQTT配置
  125. builder.Services.AddSingleton<MQTTEvents>();
  126. builder.Services.AddSingleton(new JsonSerializerOptions(JsonSerializerDefaults.Web));
  127. builder.Services.AddHostedMqttServerWithServices(x =>
  128. {
  129. x.WithDefaultEndpoint()
  130. .WithConnectionBacklog(1000)
  131. .WithPersistentSessions(true).WithKeepAlive()
  132. .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(30));
  133. }).AddMqttConnectionHandler().AddConnections().AddMqttControllers();
  134. #endregion
  135. var app = builder.Build();
  136. // Configure the HTTP request pipeline.
  137. if (!app.Environment.IsDevelopment())
  138. {
  139. app.UseExceptionHandler("/Home/Error");
  140. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  141. app.UseHsts();
  142. }
  143. app.UseRouting();
  144. app.UseCors(); //使用跨域設定
  145. app.UseAuthentication();
  146. app.UseAuthorization();
  147. app.MapControllers();
  148. app.MapHub<SignalRScreenServerHub>("/signalr/screen").RequireCors("any");
  149. app.MapConnectionHandler<MqttConnectionHandler>("/mqtt", opts => opts.WebSockets.SubProtocolSelector = protocolList => protocolList.FirstOrDefault() ?? string.Empty);
  150. var events = app.Services.GetRequiredService<MQTTEvents>();
  151. app.UseMqttServer(server =>
  152. {
  153. server.WithAttributeRouting(app.Services, allowUnmatchedRoutes: false);
  154. server.ClientSubscribedTopicAsync+=events._mqttServer_ClientSubscribedTopicAsync;// 客户端订阅主题事件
  155. server.StoppedAsync+=events._mqttServer_StoppedAsync;// 关闭后事件
  156. server.ValidatingConnectionAsync+=events._mqttServer_ValidatingConnectionAsync; // 用户名和密码验证有关
  157. server.InterceptingPublishAsync+=events._mqttServer_InterceptingPublishAsync;// 消息接收事件
  158. server.StartedAsync+=events._mqttServer_StartedAsync;// 启动后事件
  159. server.ClientUnsubscribedTopicAsync+=events._mqttServer_ClientUnsubscribedTopicAsync;// 客户端取消订阅事件
  160. server.ApplicationMessageNotConsumedAsync+=events._mqttServer_ApplicationMessageNotConsumedAsync; // 消息接收事件,应用程序消息未使用
  161. server.ClientDisconnectedAsync+=events._mqttServer_ClientDisconnectedAsync;// 客户端关闭事件
  162. server.ClientConnectedAsync+=events._mqttServer_ClientConnectedAsync;//客户端连接事件
  163. //server.InterceptingClientEnqueueAsync += events._mqttServer_InterceptingClientEnqueueAsync;//拦截客户端排队
  164. //server.ClientAcknowledgedPublishPacketAsync += events._mqttServer_ClientAcknowledgedPublishPacketAsync;//已确认发布数据包
  165. });
  166. app.Run();
  167. }
  168. }
  169. }