Startup.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using Edge.Core.Processor;
  8. using Edge.Core.Processor.Dispatcher;
  9. using Edge.Core.UniversalApi;
  10. using Microsoft.AspNetCore.Builder;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.AspNetCore.Mvc.ApiExplorer;
  14. using Microsoft.AspNetCore.Mvc.Controllers;
  15. using Microsoft.AspNetCore.Mvc.Core;
  16. using Microsoft.Extensions.Configuration;
  17. using Microsoft.Extensions.DependencyInjection;
  18. using Microsoft.Extensions.DependencyInjection.Extensions;
  19. using Microsoft.Extensions.Hosting;
  20. using Microsoft.Extensions.Logging;
  21. using Microsoft.OpenApi.Models;
  22. using MQTTnet.AspNetCore;
  23. using MQTTnet.Diagnostics;
  24. using MQTTnet.Protocol;
  25. using MQTTnet.Server;
  26. using Edge.WebHost.Hubs;
  27. using Swashbuckle.AspNetCore.SwaggerGen;
  28. namespace Edge.WebHost
  29. {
  30. public class Startup
  31. {
  32. public Startup(IConfiguration configuration)
  33. {
  34. Configuration = configuration;
  35. }
  36. public IConfiguration Configuration { get; }
  37. // This method gets called by the runtime. Use this method to add services to the container.
  38. public void ConfigureServices(IServiceCollection aspNetCoreServices)
  39. {
  40. aspNetCoreServices.AddCors(options => options.AddPolicy("cors", builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin()));
  41. aspNetCoreServices.AddLogging(loggingBuilder =>
  42. {
  43. loggingBuilder.ClearProviders();
  44. loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
  45. });//Startup.Services.GetRequiredService<ILoggerFactory>());
  46. aspNetCoreServices.AddControllersWithViews();
  47. // .AddRazorOptions(opt =>
  48. //{
  49. // opt.ViewLocationFormats.Add("/AspNetCoreWebApi/Views/{1}/{0}.cshtml");
  50. // opt.ViewLocationFormats.Add("/AspNetCoreWebApi/Views/Shared/{0}.cshtml");
  51. //});
  52. // Register the Swagger generator, defining 1 or more Swagger documents
  53. aspNetCoreServices.AddSwaggerGen(c =>
  54. {
  55. c.SwaggerDoc("v1", new OpenApiInfo { Title = "Universal Api - WebApi", Version = "v1" });
  56. c.DocumentFilter<InjectProcessorApiDocumentFilter>();
  57. // Set the comments path for the Swagger JSON and UI.
  58. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  59. var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
  60. c.IncludeXmlComments(xmlPath);
  61. });
  62. aspNetCoreServices.AddMqttWebSocketServerAdapter();
  63. aspNetCoreServices.AddSignalR();
  64. //var mqttServerOptionsBuilder = new MqttServerOptionsBuilder()
  65. // .WithoutDefaultEndpoint()
  66. // //.WithDefaultEndpointPort(mqttServerPort)
  67. // .WithConnectionValidator(
  68. // c =>
  69. // {
  70. // c.ReasonCode = MqttConnectReasonCode.Success;
  71. // }).WithSubscriptionInterceptor(
  72. // c =>
  73. // {
  74. // c.AcceptSubscription = true;
  75. // }).WithApplicationMessageInterceptor(
  76. // c =>
  77. // {
  78. // c.AcceptPublish = true;
  79. // });
  80. aspNetCoreServices
  81. .AddHostedMqttServer(mqttServer => mqttServer.WithoutDefaultEndpoint())
  82. .AddMqttConnectionHandler()
  83. .AddConnections();
  84. }
  85. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  86. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  87. {
  88. //app.UseCors();
  89. app.UseCors("cors");
  90. // Enable middleware to serve generated Swagger as a JSON endpoint.
  91. app.UseSwagger();
  92. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  93. // specifying the Swagger JSON endpoint.
  94. app.UseSwaggerUI(c =>
  95. {
  96. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Universal Api - WebApi V1");
  97. });
  98. //if (env.IsDevelopment())
  99. {
  100. app.UseDeveloperExceptionPage();
  101. }
  102. // else
  103. //{
  104. // app.UseExceptionHandler("/Home/Error");
  105. //}
  106. app.UseStaticFiles();
  107. app.UseRouting();
  108. app.UseAuthorization();
  109. app.UseEndpoints(endpoints =>
  110. {
  111. endpoints.MapControllerRoute(
  112. name: "default",
  113. pattern: "{controller=Home}/{action=Index}/{id?}");
  114. endpoints.MapHub<AlarmHub>("/alarmHub");
  115. });
  116. //app.UseEndpoints(endpoints =>
  117. //{
  118. // endpoints.MapControllerRoute(
  119. // name: "WebConsole",
  120. // pattern: "WebConsole/{controller=Home}/{action=Index}/{id?}");
  121. //});
  122. //app.UseEndpoints(endpoints =>
  123. //{
  124. // endpoints.MapMqtt("/mqtt");
  125. //});
  126. //MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
  127. //{
  128. // if (e.LogMessage?.Exception != null)
  129. // {
  130. // var trace = $">> [{e.LogMessage.Timestamp:O}] [{e.LogMessage.ThreadId}] [{e.LogMessage.Source}] [{e.LogMessage.Level}]: {e.LogMessage.Message}";
  131. // trace += Environment.NewLine + e.LogMessage.Exception.ToString();
  132. // //AppInstance?.logger?.LogInformation("Mqtt Server or client component exceptioned: " + Environment.NewLine + trace);
  133. // }
  134. //};
  135. //app.UseMqttEndpoint("/mqtt");
  136. app.UseEndpoints(endpoints =>
  137. {
  138. endpoints.MapMqtt("/mqtt");
  139. });
  140. app.UseMqttServer(mqttServer =>
  141. {
  142. //mqttServer.UseClientConnectedHandler(e =>
  143. //{
  144. // //var debug = e.ClientId;
  145. //});
  146. //mqttServer.UseClientDisconnectedHandler(e =>
  147. //{
  148. // //var debug = e.ClientId;
  149. //});
  150. //mqttServer.UseApplicationMessageReceivedHandler(async e =>
  151. //{
  152. // //var debug = e.ApplicationMessage.Topic + " " +
  153. // // Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
  154. // //if (this.logger.IsEnabled(LogLevel.Debug))
  155. // //{
  156. // // this.logger.LogDebug($"+ received msg on Topic = {e.ApplicationMessage.Topic}");
  157. // // this.logger.LogDebug($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  158. // // this.logger.LogDebug($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  159. // // this.logger.LogDebug($"+ Retain = {e.ApplicationMessage.Retain}");
  160. // //}
  161. //});
  162. });
  163. }
  164. }
  165. }