Startup.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using Autofac;
  2. using Autofac.Extensions.DependencyInjection;
  3. using FreeRedis;
  4. using FreeSql;
  5. using Microsoft.AspNetCore.Authentication;
  6. using Microsoft.AspNetCore.Authentication.JwtBearer;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.IdentityModel.Tokens;
  9. using Microsoft.OpenApi.Models;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Serialization;
  12. using NLog.Web;
  13. using SM.Core;
  14. using SM.Model.SQL;
  15. using System.Reflection;
  16. using System.Text;
  17. namespace SM.Web
  18. {
  19. ///<summary>启动器</summary>
  20. public class Startup
  21. {
  22. ///<summary>执行方法</summary>
  23. public void Run(string[] args)
  24. {
  25. try
  26. {
  27. WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
  28. builder.Logging.ClearProviders().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
  29. builder.Host.UseNLog();
  30. IServiceCollection services = builder.Services;
  31. IWebHostEnvironment env = builder.Environment;
  32. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  33. AppConfig appConfig = ConfigHelper.Get<AppConfig>("AppConfig");
  34. services.AddSingleton(appConfig);
  35. WhiteListConfig whiteListConfig = ConfigHelper.Get<WhiteListConfig>("WhiteListConfig");
  36. services.AddSingleton(whiteListConfig);
  37. builder.WebHost.UseUrls(appConfig.Urls);
  38. for (int i = 0; i < appConfig.Urls.Length; i++)
  39. {
  40. LogHelper.Debug(appConfig.Urls[i]);
  41. }
  42. ConfigureServices(services, appConfig, env);
  43. builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  44. {
  45. ConfigureContainer(builder);
  46. });
  47. WebApplication app = builder.Build();
  48. Configure(app, appConfig);
  49. app.Run();
  50. }
  51. catch (Exception ex)
  52. {
  53. LogHelper.Error($"启动错误:{ex.Message}", ex);
  54. }
  55. }
  56. private void ConfigureServices(IServiceCollection services, AppConfig appConfig, IWebHostEnvironment env)
  57. {
  58. services.AddHttpClient();
  59. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  60. //自动映射
  61. Assembly serviceAssembly = Assembly.Load("SM.Services");
  62. services.AddAutoMapper(serviceAssembly);
  63. services.AddCors(options =>
  64. {
  65. options.AddPolicy("Cors", policy =>
  66. {
  67. if (appConfig.IsDebug)
  68. {
  69. policy
  70. .AllowAnyMethod()
  71. .SetIsOriginAllowed(_ => true)
  72. .AllowAnyHeader()
  73. .AllowCredentials();
  74. }
  75. else
  76. {
  77. policy
  78. .WithOrigins(appConfig.Cors)
  79. .AllowAnyHeader()
  80. .AllowAnyMethod()
  81. .AllowCredentials();
  82. }
  83. });
  84. });
  85. JwtConfig jwtConfig = ConfigHelper.Get<JwtConfig>("JwtConfig");
  86. services.AddSingleton(jwtConfig);
  87. services.AddAuthentication(options =>
  88. {
  89. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  90. options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
  91. options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
  92. }).AddJwtBearer(options =>
  93. {
  94. options.TokenValidationParameters = new TokenValidationParameters
  95. {
  96. ValidateIssuer = true,
  97. ValidateAudience = true,
  98. ValidateLifetime = true,
  99. ValidateIssuerSigningKey = true,
  100. ValidIssuer = jwtConfig.Issuer,
  101. ValidAudience = jwtConfig.Audience,
  102. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
  103. ClockSkew = TimeSpan.Zero
  104. };
  105. }).AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
  106. //内存
  107. //services.AddMemoryCache();
  108. //MySQL
  109. MySQLConfig mySQLConfig = ConfigHelper.Get<MySQLConfig>("MySQLConfig");
  110. Func<IServiceProvider, IFreeSql> fsqlFactory = r =>
  111. {
  112. IFreeSql fsql = new FreeSqlBuilder()
  113. .UseConnectionString(DataType.MySql, mySQLConfig.Connect)
  114. //.UseMonitorCommand(cmd => Console.WriteLine($"Sql:{cmd.CommandText}"))//监听SQL语句
  115. .UseAutoSyncStructure(true) //自动同步实体结构到数据库,FreeSql不会扫描程序集,只有CRUD时才会生成表。
  116. .Build();
  117. return fsql;
  118. };
  119. services.AddSingleton<IFreeSql>(fsqlFactory);
  120. //Redis
  121. RedisConfig redisConfig = ConfigHelper.Get<RedisConfig>("RedisConfig");
  122. RedisClient redis = new RedisClient(redisConfig.Connect)
  123. {
  124. Serialize = JsonConvert.SerializeObject,
  125. Deserialize = JsonConvert.DeserializeObject
  126. };
  127. services.AddSingleton(redis);
  128. //MongoDB
  129. //services.AddScoped<IMongoContext, MongoContext>();
  130. //services.AddScoped(typeof(IMongoRepository<>), typeof(MongoRepository<>));
  131. //设置输出的首字母大小写
  132. services.AddControllers().AddNewtonsoftJson(options =>
  133. {
  134. //忽略循环引用
  135. options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  136. //默认属性输出
  137. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  138. //使用驼峰 首字母小写
  139. //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  140. //设置时间格式
  141. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  142. });
  143. //截取客户端提交的空参数
  144. services.Configure<ApiBehaviorOptions>(options =>
  145. {
  146. options.InvalidModelStateResponseFactory = actionContext =>
  147. {
  148. List<string> errors = actionContext.ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).ToList();
  149. string str = string.Join(" | ", errors);
  150. IResponseOutput response = ResponseOutput.NotOk(StatusCode.FieldNull_Error, str);
  151. return new BadRequestObjectResult(response);
  152. };
  153. });
  154. if (appConfig.IsDebug)
  155. {
  156. services.AddSwaggerGen(c =>
  157. {
  158. c.SwaggerDoc("v1", new OpenApiInfo { Title = "SM.Web", Version = "v1" });
  159. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  160. var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
  161. c.IncludeXmlComments(xmlPath);
  162. });
  163. }
  164. }
  165. private void ConfigureContainer(ContainerBuilder builder)
  166. {
  167. Assembly assemblyCore = Assembly.Load("SM.Core");
  168. builder.RegisterAssemblyTypes(assemblyCore).Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null).SingleInstance();
  169. builder.RegisterAssemblyTypes(assemblyCore).Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null).AsImplementedInterfaces().SingleInstance();
  170. var assemblyServices = Assembly.Load("SM.Services");
  171. builder.RegisterAssemblyTypes(assemblyServices).AsImplementedInterfaces().InstancePerLifetimeScope();
  172. }
  173. private void Configure(WebApplication app, AppConfig appConfig)
  174. {
  175. if (appConfig.IsDebug)
  176. {
  177. app.UseSwagger();
  178. app.UseSwaggerUI(c =>
  179. {
  180. c.SwaggerEndpoint("/swagger/v1/swagger.json", "SM.Web");
  181. });
  182. }
  183. //异常处理
  184. app.UseMiddleware<ExceptionMiddleware>();
  185. //路由
  186. app.UseRouting();
  187. //跨域
  188. app.UseCors("Cors");
  189. //认证
  190. app.UseAuthentication();
  191. //授权
  192. app.UseAuthorization();
  193. //默认访问
  194. //app.UseDefaultFiles();
  195. //静态文件访问(开启所以文件访问权限)
  196. //app.UseStaticFiles(new StaticFileOptions
  197. //{
  198. // ServeUnknownFileTypes = true
  199. //});
  200. if (!app.Environment.IsDevelopment())
  201. {
  202. //https
  203. app.UseHttpsRedirection();
  204. }
  205. //配置端点
  206. app.MapControllers();
  207. //在项目启动时,从容器中获取IFreeSql实例,并执行一些操作:同步表,种子数据,FluentAPI等
  208. using (IServiceScope serviceScope = app.Services.CreateScope())
  209. {
  210. var fsql = serviceScope.ServiceProvider.GetRequiredService<IFreeSql>();
  211. //同步的实体类
  212. fsql.CodeFirst.SyncStructure<AccountEntity>();
  213. }
  214. LogHelper.Debug("启动成功");
  215. }
  216. }
  217. }