Startup.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. using System.IO;
  2. using GxPress.Api.ServiceExtensions;
  3. using GxPress.Common.AppOptions;
  4. using GxPress.Common.Middleware;
  5. using GxPress.Common.Tools;
  6. using GxPress.Repository.Implement;
  7. using GxPress.Repository.Interface;
  8. using GxPress.Service.Implement;
  9. using GxPress.Service.Interface;
  10. using Microsoft.AspNetCore.Builder;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.AspNetCore.Http.Features;
  14. using Microsoft.AspNetCore.Mvc;
  15. using Microsoft.Extensions.Configuration;
  16. using Microsoft.Extensions.DependencyInjection;
  17. using Microsoft.Extensions.FileProviders;
  18. using Microsoft.Extensions.Hosting;
  19. using Newtonsoft.Json;
  20. using Newtonsoft.Json.Serialization;
  21. using Quartz;
  22. using Quartz.Impl;
  23. using SqlSugar;
  24. namespace GxPress.Api
  25. {
  26. public class Startup
  27. {
  28. public IConfiguration Configuration { get; }
  29. public Startup(IConfiguration configuration)
  30. {
  31. Configuration = configuration;
  32. ConfigHelper.Configs = Configuration;
  33. }
  34. // This method gets called by the runtime. Use this method to add services to the container.
  35. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  36. public void ConfigureServices(IServiceCollection services)
  37. {
  38. services.AddSingleton(new SqlSugarClient(new ConnectionConfig
  39. {
  40. ConnectionString = "server=47.95.221.96;uid=root;pwd=siteservercms88;database=ccpph_tede;MultipleActiveResultSets=true",//必填, 数据库连接字符串
  41. DbType = DbType.SqlServer, //必填, 数据库类型
  42. IsAutoCloseConnection = true, //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
  43. InitKeyType = InitKeyType.SystemTable //默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息
  44. }));
  45. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  46. services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  47. // services.AddSingleton<IUserService, UserService>();
  48. services.AddSingleton<IApiLogService, ApiLogService>();
  49. services.AddControllers().AddNewtonsoftJson(options =>
  50. {
  51. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  52. //options.UseCamelCasing(true);
  53. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  54. //// 忽略循环引用
  55. //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  56. //// 如字段为null值,该字段不会返回到前端
  57. // options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
  58. }).AddJsonOptions(options =>
  59. {
  60. options.JsonSerializerOptions.PropertyNamingPolicy = null;
  61. }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
  62. //文件上传限制60MB
  63. services.Configure<FormOptions>(options =>
  64. {
  65. options.MultipartBodyLengthLimit = 60000000;
  66. });
  67. //数据库
  68. var databaseSection = Configuration.GetSection("Database");
  69. var cacheSection = Configuration.GetSection("Cache:ConnectionString");
  70. var storageOptions = Configuration.GetSection("Storage").Get<StorageOptions>();
  71. services.Configure<DatabaseOptions>(databaseSection);
  72. services.AddDistributedCache(cacheSection.Value);
  73. services.AddStorage(storageOptions);
  74. services.Configure<ApiBehaviorOptions>(o =>
  75. {
  76. o.InvalidModelStateResponseFactory = actionContext =>
  77. new BadRequestObjectResult(JsonConvert.SerializeObject(new
  78. {
  79. Message = "参数错误",
  80. StackTrace = JsonConvert.SerializeObject(actionContext.ModelState)
  81. }));
  82. });
  83. // var client = new CSRedisClient(redisSection.Value);
  84. // //初始化 RedisHelper
  85. // RedisHelper.Initialization(client);
  86. // //注册分布式缓存
  87. // var options = Options.Create(new Microsoft.Extensions.Caching.Redis.RedisCacheOptions
  88. // {
  89. // Configuration = redisSection.Value,
  90. // InstanceName = string.Empty,
  91. // });
  92. // services.AddSingleton<IDistributedCache>(new RedisCache(options));
  93. services.AddRepositories();
  94. services.AddServices();
  95. services.AddMappers();
  96. services.AddJwtAuthentication(Configuration);
  97. services.AddCors(options =>
  98. {
  99. options.AddPolicy(
  100. "AllowAny",
  101. x =>
  102. {
  103. x.AllowAnyHeader()
  104. .AllowAnyMethod()
  105. .SetIsOriginAllowed(_ => true)
  106. .AllowCredentials();
  107. });
  108. });
  109. services.AddSwashbuckle();
  110. }
  111. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  112. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  113. {
  114. //var provider = new FileExtensionContentTypeProvider();
  115. // // Add new mappings
  116. // provider.Mappings[".epub"] = "application/octet-stream";
  117. if (env.IsDevelopment())
  118. {
  119. app.UseDeveloperExceptionPage();
  120. }
  121. //最上层的自定义异常处理中间件
  122. app.UseMiddleware<ExceptionMiddleware>();
  123. app.UseRouting();
  124. app.UseJwtAuthorization();
  125. var cachePeriod = env.IsDevelopment() ? "600" : "604800";
  126. app.UseStaticFiles(new StaticFileOptions
  127. {
  128. //ContentTypeProvider = provider,
  129. //非标准类型
  130. ServeUnknownFileTypes = true,
  131. //返回类型
  132. DefaultContentType = "application/octet-stream",
  133. OnPrepareResponse = ctx =>
  134. {
  135. // Requires the following import:
  136. // using Microsoft.AspNetCore.Http;
  137. ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
  138. ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", $"X-Requested-With");
  139. ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", $"*");
  140. ctx.Context.Response.Headers.Append("Access-Control-Allow-Methods", $"GET,POST,OPTIONS");
  141. ctx.Context.Response.Headers.Append("Connection", $"keep-alive");
  142. }
  143. });
  144. // app.UseStaticFiles(new StaticFileOptions
  145. // {
  146. // FileProvider = new PhysicalFileProvider(
  147. // Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
  148. // RequestPath = "",
  149. // ContentTypeProvider = provider
  150. // });
  151. app.UseDirectoryBrowser(new DirectoryBrowserOptions
  152. {
  153. FileProvider = new PhysicalFileProvider(
  154. Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
  155. RequestPath = "/MyImages"
  156. });
  157. app.UseCors("AllowAny");
  158. app.UseSwashbuckle();
  159. app.UseEndpoints(endpoints =>
  160. {
  161. endpoints.MapControllers();
  162. endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
  163. });
  164. }
  165. }
  166. }