Program.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. using Infrastructure;
  2. using Microsoft.AspNetCore.Authentication.JwtBearer;
  3. using Microsoft.AspNetCore.DataProtection;
  4. using ZR.Admin.WebApi.Framework;
  5. using Hei.Captcha;
  6. using Infrastructure.Extensions;
  7. using ZR.Admin.WebApi.Extensions;
  8. using ZR.Admin.WebApi.Filters;
  9. using ZR.Admin.WebApi.Middleware;
  10. using ZR.Admin.WebApi.Hubs;
  11. using NLog.Web;
  12. var builder = WebApplication.CreateBuilder(args);
  13. builder.Host.UseNLog();
  14. // Add services to the container.
  15. builder.Services.AddControllers();
  16. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  17. builder.Services.AddEndpointsApiExplorer();
  18. builder.Services.AddSwaggerGen();
  19. //注入HttpContextAccessor
  20. builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  21. var corsUrls = builder.Configuration["corsUrls"]?.Split(',', StringSplitOptions.RemoveEmptyEntries);
  22. //配置跨域
  23. builder.Services.AddCors(c =>
  24. {
  25. c.AddPolicy("Policy", policy =>
  26. {
  27. policy.WithOrigins(corsUrls == null ? Array.Empty<string>() : corsUrls)
  28. .AllowAnyHeader()//允许任意头
  29. .AllowCredentials()//允许cookie
  30. .AllowAnyMethod();//允许任意方法
  31. });
  32. });
  33. //注入SignalR实时通讯,默认用json传输
  34. builder.Services.AddSignalR();
  35. //消除Error unprotecting the session cookie警告
  36. builder.Services.AddDataProtection()
  37. .PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));
  38. //普通验证码
  39. builder.Services.AddHeiCaptcha();
  40. //builder.Services.AddSession();
  41. builder.Services.AddHttpContextAccessor();
  42. //绑定整个对象到Model上
  43. builder.Services.Configure<OptionsSetting>(builder.Configuration);
  44. //jwt 认证
  45. builder.Services.AddAuthentication(options =>
  46. {
  47. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  48. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  49. }).AddCookie()
  50. .AddJwtBearer(o =>
  51. {
  52. o.TokenValidationParameters = JwtUtil.ValidParameters();
  53. });
  54. //InternalApp.InternalServices = builder.Services;
  55. builder.Services.AddAppService();
  56. builder.Services.AddSingleton(new AppSettings(builder.Configuration));
  57. //开启计划任务
  58. builder.Services.AddTaskSchedulers();
  59. //初始化db
  60. DbExtension.AddDb(builder.Configuration);
  61. //注册REDIS 服务
  62. Task.Run(() =>
  63. {
  64. //RedisServer.Initalize();
  65. });
  66. builder.Services.AddMvc(options =>
  67. {
  68. options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
  69. })
  70. .AddJsonOptions(options =>
  71. {
  72. options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
  73. options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeNullConverter());
  74. });
  75. builder.Services.AddSwaggerConfig();
  76. // 显示logo
  77. builder.Services.AddLogo();
  78. var app = builder.Build();
  79. InternalApp.ServiceProvider = app.Services;
  80. if (builder.Configuration["InitDb"].ParseToBool() == true)
  81. {
  82. app.Services.InitDb();
  83. }
  84. app.UseSwagger();
  85. //使可以多次多去body内容
  86. app.Use((context, next) =>
  87. {
  88. context.Request.EnableBuffering();
  89. if (context.Request.Query.TryGetValue("access_token", out var token))
  90. {
  91. context.Request.Headers.Add("Authorization", $"Bearer {token}");
  92. }
  93. return next();
  94. });
  95. //开启访问静态文件/wwwroot目录文件,要放在UseRouting前面
  96. app.UseStaticFiles();
  97. //开启路由访问
  98. app.UseRouting();
  99. app.UseCors("Policy");//要放在app.UseEndpoints前。
  100. //app.UseHttpsRedirection();
  101. app.UseAuthentication();
  102. app.UseAuthorization();
  103. //开启缓存
  104. app.UseResponseCaching();
  105. //恢复/启动任务
  106. app.UseAddTaskSchedulers();
  107. //使用全局异常中间件
  108. app.UseMiddleware<GlobalExceptionMiddleware>();
  109. //解决ExcelDataReader读取流时出现Encoding 1252错误
  110. System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
  111. //设置socket连接
  112. app.MapHub<MessageHub>("/msgHub");
  113. app.MapControllerRoute(
  114. name: "default",
  115. pattern: "{controller=Home}/{action=Index}/{id?}");
  116. app.MapControllers();
  117. app.Run();