Startup.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ServiceModel;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Http.Features;
  8. using Microsoft.AspNetCore.Rewrite;
  9. using Microsoft.AspNetCore.StaticFiles;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.Extensions.DependencyInjection;
  12. using Microsoft.Extensions.FileProviders;
  13. using Microsoft.Extensions.Hosting;
  14. using MySystem.PublicClass.GraphQL;
  15. using System.Text;
  16. using Microsoft.IdentityModel.Tokens;
  17. using System.Linq;
  18. using Microsoft.AspNetCore.Server.Kestrel.Core;
  19. namespace MySystem
  20. {
  21. public class Startup
  22. {
  23. public Startup(IConfiguration configuration)
  24. {
  25. Configuration = configuration;
  26. }
  27. public IConfiguration Configuration { get; }
  28. // This method gets called by the runtime. Use this method to add services to the container.
  29. public void ConfigureServices(IServiceCollection services)
  30. {
  31. services.AddControllersWithViews();
  32. services.AddRouting(options =>
  33. {
  34. options.LowercaseUrls = true;
  35. });
  36. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  37. services.Configure<Setting>(Configuration.GetSection("Setting"));
  38. services.Configure<KestrelServerOptions>(options =>
  39. {
  40. options.AllowSynchronousIO = true;
  41. });
  42. services.Configure<IISServerOptions>(options =>
  43. {
  44. options.AllowSynchronousIO = true;
  45. });
  46. // 测试后必须注释
  47. // services.AddCors(option => option.AddPolicy("cors", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().SetIsOriginAllowed(_ => true)));
  48. // 测试后必须注释
  49. services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true).Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
  50. services.AddMvc(options =>
  51. {
  52. options.EnableEndpointRouting = false;
  53. options.Filters.Add(typeof(GlobalExceptions));
  54. });
  55. services.AddSession(options =>
  56. {
  57. // 设置 Session 过期时间
  58. options.IdleTimeout = TimeSpan.FromHours(1);
  59. options.Cookie.HttpOnly = true;
  60. });
  61. services.AddSingleton<IRepository, Repository>();
  62. services.Configure<FormOptions>(x =>
  63. {
  64. x.MultipartBodyLengthLimit = 50 * 1024 * 1024;//不到300M
  65. });
  66. //生成密钥
  67. var symmetricKeyAsBase64 = Configuration["Setting:JwtSecret"];
  68. var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
  69. var signingKey = new SymmetricSecurityKey(keyByteArray);
  70. //认证参数
  71. services.AddAuthentication("Bearer").AddJwtBearer(o =>
  72. {
  73. o.TokenValidationParameters = new TokenValidationParameters
  74. {
  75. ValidateIssuerSigningKey = true,//是否验证签名,不验证的画可以篡改数据,不安全
  76. IssuerSigningKey = signingKey,//解密的密钥
  77. ValidateIssuer = true,//是否验证发行人,就是验证载荷中的Iss是否对应ValidIssuer参数
  78. // ValidIssuer = Configuration["Setting:JwtIss"],//发行人
  79. IssuerValidator = (m, n, z) =>
  80. {
  81. return n.Issuer;
  82. },
  83. ValidateAudience = true,//是否验证订阅人,就是验证载荷中的Aud是否对应ValidAudience参数
  84. // ValidAudience = Configuration["Setting:JwtAud"],//订阅人
  85. AudienceValidator = (m, n, z) =>
  86. {
  87. string check = RedisDbconn.Instance.Get<string>("utoken:" + n.Issuer);
  88. return m != null && m.FirstOrDefault().Equals(check);
  89. },
  90. ValidateLifetime = true,//是否验证过期时间,过期了就拒绝访问
  91. ClockSkew = TimeSpan.Zero,//这个是缓冲过期时间,也就是说,即使我们配置了过期时间,这里也要考虑进去,过期时间+缓冲,默认好像是7分钟,你可以直接设置为0
  92. RequireExpirationTime = true,
  93. };
  94. });
  95. // services.AddHostedService<PublicService>();
  96. // services.AddHostedService<PublicErrService>();
  97. //services.AddHttpContextAccessor();
  98. string appkey = Configuration["Setting:AppKey"];
  99. string appid = Configuration["Setting:AppId"];
  100. string checkurl = Configuration["Setting:CheckUrl"];
  101. string serviceurl = Configuration["Setting:WebServiceUrl"];
  102. string schemeurl = Configuration["Setting:DbSchemeUrl"];
  103. MySystemLib.SystemPublicFuction.appkey = appkey;
  104. MySystemLib.SystemPublicFuction.appid = appid;
  105. MySystemLib.SystemPublicFuction.checkurl = checkurl;
  106. MySystemLib.SystemPublicFuction.appcheck = "success";
  107. // var binding = new BasicHttpBinding();
  108. // binding.MaxReceivedMessageSize = 2147483647;
  109. // var endpoint = new EndpointAddress(Configuration["Setting:WebServiceUrl"]);
  110. // var factory = new ChannelFactory<GetDataBaseSoap>(binding, endpoint);
  111. // var callClient = factory.CreateChannel();
  112. // DataBaseRequestBody body = new DataBaseRequestBody();
  113. // body.appid = appid;
  114. // body.appkey = appkey;
  115. // var request = new DataBaseRequest(body);
  116. // var wait = callClient.DataBaseAsync(request);
  117. // wait.Wait();
  118. // tempuri.org.CustomerTables[] servicetable = wait.Result.Body.DataBaseResult;
  119. // Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
  120. // foreach (tempuri.org.CustomerTables subtable in servicetable)
  121. // {
  122. // Dictionary<string, string> Columns = new Dictionary<string, string>();
  123. // foreach (tempuri.org.CustomerColumns subcolumn in subtable.Columns)
  124. // {
  125. // Columns.Add(subcolumn.FieldName, subcolumn.FieldType);
  126. // }
  127. // tables.Add(subtable.TableName, Columns);
  128. // }
  129. // servicetable = null;
  130. // string database = Library.function.GetWebRequest(serviceurl + "?appid=" + appid + "&appkey=" + appkey);
  131. // Dictionary<string, Dictionary<string, string>> tables = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(database);
  132. // MySystemLib.SystemPublicFuction.dbtables = tables;
  133. // string schemeString = Library.function.GetWebRequest(schemeurl + "?appid=" + appid + "&appkey=" + appkey);
  134. // RedisDbconn.Instance.Set("dbscheme", Newtonsoft.Json.JsonConvert.DeserializeObject<List<MySystem.DbScheme>>(schemeString));
  135. string conn = Configuration["Setting:SqlConnStr"];
  136. Dictionary<string, Dictionary<string, string>> tables = new Dictionary<string, Dictionary<string, string>>();
  137. System.Data.DataTable tablecollection = Library.CustomerSqlConn.dtable("select DISTINCT TABLE_NAME from information_schema.columns where table_schema = 'KxsSpServer'", conn);
  138. foreach (System.Data.DataRow subtable in tablecollection.Rows)
  139. {
  140. Dictionary<string, string> Columns = new Dictionary<string, string>();
  141. System.Data.DataTable columncollection = Library.CustomerSqlConn.dtable("select COLUMN_NAME,DATA_TYPE from information_schema.columns where table_schema = 'KxsSpServer' and TABLE_NAME='" + subtable["TABLE_NAME"].ToString() + "'", conn);
  142. foreach (System.Data.DataRow column in columncollection.Rows)
  143. {
  144. string datatype = column["DATA_TYPE"].ToString();
  145. if (datatype == "decimal")
  146. {
  147. datatype = "numeric";
  148. }
  149. Columns.Add(column["COLUMN_NAME"].ToString(), datatype);
  150. }
  151. tables.Add(subtable["TABLE_NAME"].ToString(), Columns);
  152. }
  153. MySystemLib.SystemPublicFuction.dbtables = tables;
  154. RedisDbconn.csredis = new CSRedis.CSRedisClient(Configuration["Setting:RedisConnStr"]);
  155. }
  156. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  157. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  158. {
  159. if (env.IsDevelopment())
  160. {
  161. app.UseDeveloperExceptionPage();
  162. // app.UseExceptionHandler("/Home/Error");
  163. }
  164. else
  165. {
  166. app.UseExceptionHandler("/Home/Error");
  167. app.UseHsts();
  168. }
  169. Library.ConfigurationManager.EnvironmentFlag = 2;
  170. Library.function.WritePage("/", "WebRootPath.txt", env.WebRootPath);
  171. // app.UseStatusCodePagesWithReExecute("/public/errpage/pc/{0}.html");
  172. // RequestDelegate handler = async context =>
  173. // {
  174. // var response = context.Response;
  175. // if (response.StatusCode < 500)
  176. // {
  177. // response.("/public/errpage/pc/{0}.html");
  178. // }
  179. // };
  180. // app.UseStatusCodePages(builder => builder.Run(handler));
  181. app.UseStaticFiles();
  182. // app.UseStaticFiles(new StaticFileOptions
  183. // {
  184. // FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory + "/static"),
  185. // RequestPath = "/static"
  186. // });
  187. // app.UseStaticFiles(new StaticFileOptions
  188. // {
  189. // FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory + "/" + Configuration["Setting:Database"]),
  190. // RequestPath = "/" + Configuration["Setting:Database"]
  191. // });
  192. app.UseStaticFiles(new StaticFileOptions
  193. {
  194. ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
  195. {
  196. { ".apk", "application/vnd.android.package-archive" }
  197. })
  198. });
  199. app.UseCors("cors");
  200. app.UseAuthentication();
  201. app.UseRouting();
  202. app.UseAuthorization();
  203. app.UseSession();
  204. app.UseEndpoints(endpoints =>
  205. {
  206. endpoints.MapControllerRoute(
  207. name: "default",
  208. pattern: "{controller=Home}/{action=Index}/{Id?}");
  209. });
  210. // 必须执行
  211. GetSpTimer.Instance.Start(); //定时从redis抓取第三方接收数据
  212. SpNoticeHelper.Instance.Start();
  213. LogHelper.Instance.Start();
  214. CheckWifiData.Instance.Start(); //解析wifi设备通知数据
  215. // 必须执行
  216. }
  217. }
  218. }