颐和api

Startup.cs 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Api.SignToken;
  8. using AutoMapper;
  9. using MadRunFabric.Common;
  10. using MadRunFabric.Common.Options;
  11. using Microsoft.AspNetCore.Authentication.JwtBearer;
  12. using Microsoft.AspNetCore.Authorization;
  13. using Microsoft.AspNetCore.Builder;
  14. using Microsoft.AspNetCore.Hosting;
  15. using Microsoft.AspNetCore.Mvc.Versioning;
  16. using Microsoft.Extensions.Configuration;
  17. using Microsoft.Extensions.DependencyInjection;
  18. using Microsoft.Extensions.Logging;
  19. using Microsoft.Extensions.Options;
  20. using Microsoft.IdentityModel.Tokens;
  21. using NLog.Extensions.Logging;
  22. using NLog.Web;
  23. using Pivotal.Discovery.Client;
  24. using OnLineChatApi.Class;
  25. using OnLineChatApi.IRepositories;
  26. using OnLineChatApi.Repositories;
  27. namespace OnLineChatApi
  28. {
  29. public class Startup
  30. {
  31. public Startup(IHostingEnvironment env)
  32. {
  33. Configuration = new ConfigurationBuilder()
  34. .SetBasePath(env.ContentRootPath)
  35. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  36. .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
  37. .AddEnvironmentVariables()
  38. .Build();
  39. }
  40. public IConfiguration Configuration { get; }
  41. // This method gets called by the runtime. Use this method to add services to the container.
  42. public void ConfigureServices(IServiceCollection services)
  43. {
  44. #region Cors 配置
  45. //生产环境 的cors
  46. services.AddCors(options =>
  47. {
  48. options.AddPolicy("CorsProd",
  49. builder => builder.AllowAnyOrigin()
  50. //builder => builder.WithOrigins(Configuration["Cors"].Split(','))
  51. .AllowAnyMethod()
  52. .AllowAnyHeader()
  53. .AllowCredentials().SetPreflightMaxAge(TimeSpan.FromMinutes(30)));
  54. });
  55. //开发环境的cors
  56. services.AddCors(options =>
  57. {
  58. options.AddPolicy("CorsDev",
  59. builder => builder.AllowAnyOrigin()
  60. .AllowAnyMethod()
  61. .AllowAnyHeader()
  62. .AllowCredentials().SetPreflightMaxAge(TimeSpan.FromMinutes(30)));
  63. });
  64. #endregion
  65. #region 授权配置
  66. //读取jwt配置文件
  67. var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"].ToString()));
  68. var tokenValidationParameters = new TokenValidationParameters
  69. {
  70. ValidateIssuerSigningKey = true,
  71. IssuerSigningKey = signingKey,
  72. ValidateIssuer = true,
  73. ValidIssuer = Configuration["Jwt:Issuer"].ToString(),//发行人
  74. ValidateAudience = true,
  75. ValidAudience = Configuration["Jwt:Audience"].ToString(),//订阅人
  76. ValidateLifetime = true,
  77. ClockSkew = TimeSpan.Zero,
  78. RequireExpirationTime = true,
  79. };
  80. services.AddAuthentication(options =>
  81. {
  82. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  83. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  84. })
  85. .AddJwtBearer(o =>
  86. {
  87. o.RequireHttpsMetadata = false;
  88. o.TokenValidationParameters = tokenValidationParameters;
  89. o.Events = new JwtBearerEvents
  90. {
  91. OnTokenValidated = context =>
  92. {
  93. if (context.Request.Path.Value.ToString() == "/api/logout")
  94. {
  95. var token = ((context as TokenValidatedContext).SecurityToken as JwtSecurityToken).RawData;
  96. }
  97. return Task.CompletedTask;
  98. }
  99. };
  100. });
  101. #endregion
  102. #region redis配置
  103. services.AddDistributedRedisCache(options =>
  104. {
  105. options.InstanceName = Configuration["Redis:InstanceName"].ToString();
  106. options.Configuration = $"{Configuration["Redis:HostName"].ToString()}:{Configuration["Redis:Port"].ToString()},allowAdmin=true,password={Configuration["Redis:Password"].ToString()},defaultdatabase={Configuration["Redis:Defaultdatabase"].ToString()}";
  107. });
  108. #endregion
  109. services.AddSingleton<IConfiguration>(Configuration);
  110. //注入授权Handler
  111. services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
  112. services.AddSingleton<IPermissionService, PermissionService>();
  113. #region 版本控制
  114. services.AddApiVersioning(Options =>
  115. {
  116. Options.ReportApiVersions = true;//可选,为true API返回响应标头中支持的版本信息
  117. Options.ApiVersionReader = new QueryStringApiVersionReader(parameterName: "api-version");
  118. Options.AssumeDefaultVersionWhenUnspecified = true;
  119. Options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(6, 0);
  120. });
  121. #endregion
  122. #region AutoMapper
  123. services.AddAutoMapper();
  124. #endregion
  125. services.AddMvc(options =>
  126. {
  127. options.Filters.Add<ActionFilter>();
  128. options.Filters.Add(new ExceptionFilter());
  129. }).AddJsonOptions(op => op.SerializerSettings.ContractResolver =
  130. new Newtonsoft.Json.Serialization.DefaultContractResolver());
  131. #region Mongodb配置
  132. services.Configure<MongodbOptions>(options =>
  133. {
  134. options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
  135. options.Database = Configuration.GetSection("MongoConnection:Database").Value;
  136. });
  137. #endregion
  138. #region steeltoe
  139. services.AddDiscoveryClient(Configuration);
  140. #endregion
  141. #region SignalR
  142. services.AddSignalR(hubOptions =>
  143. {
  144. hubOptions.EnableDetailedErrors = true;
  145. hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(30);
  146. });
  147. #endregion
  148. //注入授权Handler
  149. services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
  150. services.AddSingleton<IPermissionService, PermissionService>();
  151. services.AddSingleton<ISignTokenService, SignTokenService>();
  152. services.AddTransient<IChat_UserRepository, Chat_UserRepository>();
  153. services.AddTransient<IChat_InOutRepository, Chat_InOutRepository>();
  154. services.AddTransient<IChat_MessageRepository, Chat_MessageRepository>();
  155. services.AddTransient<IChat_ProcessRepository, Chat_ProcessRepository>();
  156. services.AddTransient<IChat_SessionRepository, Chat_SessionRepository>();
  157. services.AddTransient<ISys_DictionaryValueRepository, Sys_DictionaryValueRepository>();
  158. }
  159. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  160. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  161. {
  162. if (env.IsProduction())
  163. {
  164. app.UseCors("CorsProd");
  165. }
  166. else
  167. {
  168. app.UseCors("CorsDev");
  169. app.UseDeveloperExceptionPage();
  170. app.UseDatabaseErrorPage();
  171. app.UseBrowserLink();
  172. }
  173. app.UseAuthentication();
  174. app.UseSignalR(routes =>
  175. {
  176. routes.MapHub<ChatHub>("/chathub");
  177. });
  178. app.UseWebSockets();
  179. app.UseMvc();
  180. #region steeltoe
  181. app.UseDiscoveryClient();
  182. #endregion
  183. #region Nlog 引入
  184. loggerFactory.AddNLog();//添加NLog
  185. env.ConfigureNLog("nlog.config");//读取Nlog配置文件
  186. app.AddNLogWeb();
  187. #endregion
  188. }
  189. }
  190. }