Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //添加过滤器
            services.AddMvc(o => o.Filters.Add(typeof(GlobalExceptions))).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());

            //注入EF上下文,注意生命周期是Scoped,即在同一个作用域中访问到的EF上下文为同一个,便于使用事务
            services.AddDbContext <EFDbcontext>(x => x.UseSqlServer(ConfigHelper.GetValue <string>("ConnectionsStrings:Development")), ServiceLifetime.Scoped);

            //注入Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version = "v1",
                    Title   = "WebApplication1"
                });
                options.ResolveConflictingActions(x => x.First());
                var xmlPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "WebApplication1.xml");
                options.IncludeXmlComments(xmlPath);
            });

            //自动注入BLL下面的所有继承IDependency接口的类,
            var totalAssembly = new[]
            {
                Assembly.Load("BLL")
            };

            services.RegisterAssembliesTransient(totalAssembly);

            DIHelper.ServiceProvider = services.BuildServiceProvider();

            //添加AutoMapper映射关系
            services.AddAutoMapper(MapperRegister.MapType());
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                // options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            services.AddHttpClient();

            services.AddHttpClient("House", c =>
            {
                c.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
                c.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
                c.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
            })
            .ConfigurePrimaryHttpMessageHandler(x => new HouseHandler());

            services.AddDbContext <ZYContext>(options =>
                                              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddAutoMapper(MapperRegister.MapType());

            // 依赖注入服务
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IUserAppService, UserAppService>();
            services.AddScoped <IMenuRepository, MenuRepository>();
            services.AddScoped <IMenuAppService, MenuAppService>();
            services.AddScoped <IHouseRepository, HouseRepository>();
            services.AddScoped <IHouseAppService, HouseAppService>();
            services.AddScoped <IDepartmentRepository, DepartmentRepository>();
            services.AddScoped <IDepartmentAppService, DepartmentAppService>();
            services.AddScoped <IRoleRepository, RoleRepository>();
            services.AddScoped <IRoleAppService, RoleAppService>();

            services.AddSession();

            // Add Hangfire services.
            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
            {
                CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
                QueuePollInterval            = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                UsePageLocksOnDequeue        = true,
                DisableGlobalLocks           = true
            }));

            // Add the processing server as IHostedService
            services.AddHangfireServer();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Пример #3
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            MapperRegister.Register();

            var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(
                new MyPegasus.DataAccess.Migrations.Configuration());

            dbMigrator.Update();
        }
Пример #4
0
        /// <summary>
        /// 服务配置
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.Filters.Add <ApiActionResultAttribute>();
                options.Filters.Add(new AuthorizeFilter());
            });

            services.AddIdentityServerForConfig(IdentityServerConfig.ApiResources, IdentityServerConfig.Clients,
                                                IdentityServerConfig.ApiScopes);

            services.AddAuthenticationForJwtBearer(Configuration["applicationUrl"], "api1");

            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "T.Core", Version = "v1"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                s.IncludeXmlComments(xmlPath);
                s.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "Applications.Service.xml"));
                s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description  = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme       = "Bearer"
                });
                s.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        }, new string[] { }
                    }
                });
            });
            services.AddDbContext <TestDbContext>(opt =>
                                                  opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));

            services.AddAutoMapper(MapperRegister.MapType());
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Appsettings(Env.ContentRootPath));

            services.Configure <Authentication>(Configuration.GetSection("Authentication"));
            //cookie 身份验证
            services.AddAuthentication(Configuration["Authentication:CookieAuthenticationScheme"])
            .AddCookie(Configuration["Authentication:CookieAuthenticationScheme"], options =>
            {
                options.LoginPath          = "/home/login";
                options.ReturnUrlParameter = "returnurl";
                options.Cookie.Name        = Configuration["Authentication:CookieName"];
                options.Cookie.Domain      = Configuration["Authentication:CookieDomain"];
            });

            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.AddUnitOfWork <IRongboUnitOfWork, RongboUnitOfWork>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("MySqlServer"),
                                     op =>
                {
                    op.UseRowNumberForPaging();
                });
            });
            services.AddAutoMapper(MapperRegister.MapType());

            services.AddNLog();

            services.AddControllersWithViews(o =>
            {
                o.Filters.Add(typeof(GlobalExceptionsFilter));
            }).AddNewtonsoftJson(options => {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = GlobalSettings.JsonSettings.ReferenceLoopHandling;
                //不使用驼峰样式的key
                options.SerializerSettings.ContractResolver = GlobalSettings.JsonSettings.ContractResolver;
                //设置时间格式
                options.SerializerSettings.DateFormatString = GlobalSettings.JsonSettings.DateFormatString;

                options.SerializerSettings.ObjectCreationHandling = GlobalSettings.JsonSettings.ObjectCreationHandling;
            });
        }
Пример #6
0
        public virtual void Start()
        {
            var serviceProvider = new ServiceCollection();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");
            var config = builder.Build();

            serviceProvider.AddSingleton <IConfiguration>(context => config);

            var env = new SysHostEnvironment {
                EnvironmentName         = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
                ApplicationName         = AppDomain.CurrentDomain.FriendlyName,
                ContentRootPath         = AppDomain.CurrentDomain.BaseDirectory,
                ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory),
                WebRootPath             = AppDomain.CurrentDomain.BaseDirectory,
                WebRootFileProvider     = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory),
            };

            serviceProvider.AddSingleton(typeof(IWebHostEnvironment), env);

            var seqServer   = config.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(levelSwitch)
                         .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.Seq(seqServer)
                         .WriteTo.Stackify(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                         .CreateLogger();
            serviceProvider.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            // asp.net
            serviceProvider.AddSingleton(PlatformServices.Default.Application);
            serviceProvider.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            serviceProvider.AddSingleton <DiagnosticSource>(new DiagnosticListener("Microsoft.AspNetCore"));
            serviceProvider.AddSingleton <DiagnosticListener>(new DiagnosticListener("Microsoft.AspNetCore"));
            serviceProvider.Configure <RazorViewEngineOptions>(options =>
            {
            });
            serviceProvider.AddRazorPages();
            serviceProvider.AddMvc();


            // cache
            serviceProvider.Configure <CacheOptions>(config.GetSection("Cache"));
            var cacheOptions = config.GetSection("Cache").Get <CacheOptions>();

            serviceProvider.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheOptions.RedisConfiguration;
                options.InstanceName  = cacheOptions.RedisInstanceName;
            });
            serviceProvider.AddDistributedMemoryCache();


            //automapper
            serviceProvider.AddAutoMapper(typeof(BaseTest));
            MapperRegister.Register();


            var result = IoCRegister.Register(serviceProvider, config);

            Syinpo.Core.IoC.Init(result.Item1, result.Item2);
        }
Пример #7
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();


            services.AddHttpClient();
            services.AddHttpClient("monitor");
            services.AddHealthChecks().AddCheck <RandomHealthCheck>("random");


            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Warning);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));



            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddHostedService <HealthCheckWorker>();



            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration        = cacheOptions.RedisConfiguration;
                options.InstanceName         = cacheOptions.RedisInstanceName;
                options.ConfigurationOptions = ConnectionOptions.Option;
            });
            services.AddDistributedMemoryCache();


            //signalr
            services.Configure <SqlBusOptions>(Configuration.GetSection("SqlBus"));
            var sqlBusOptions = Configuration.GetSection("SqlBus").Get <SqlBusOptions>();

            if (sqlBusOptions.UseSignalrRedis)
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                })
                .AddJsonProtocol()
                .AddStackExchangeRedis(cacheOptions.RedisConfiguration, options =>
                {
                    options.Configuration.ChannelPrefix = "SigRis";
                });
            }
            else
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                });
            }
            // signalrBus
            services.AddSignalrBusServer();


            // Monitor
            services.Configure <MonitorOptions>(Configuration.GetSection("Monitor"));
            var monitorOptions = Configuration.GetSection("Monitor").Get <MonitorOptions>();

            services.AddSingleton <MonitorExporter>();
            services.AddOpenTelemetry((sp, builder) =>
            {
                builder.SetSampler(new AlwaysSampleSampler());
                builder.UseMonitor(sp).AddRequestCollector().AddDependencyCollector();
            });
            services.AddScoped(resolver => resolver.GetService <TracerFactory>().GetTracer("syinpo-api-tracer"));
            if (monitorOptions.UseMonitor)
            {
                services.AddHostedService <MonitorWorker>();
            }


            // 服务总线
            services.Configure <CapBusOptions>(Configuration.GetSection("CapBus"));
            var capBusOptions = Configuration.GetSection("CapBus").Get <CapBusOptions>();

            services.AddCap(x =>
            {
                string capConnectionString = Configuration.GetConnectionString("CapConnection");
                x.UseSqlServer(capConnectionString);

                string rabbitmqConnectionString = capBusOptions.RabbitMQConnection;
                x.UseRabbitMQ(mq =>
                {
                    mq.UserName    = "******";
                    mq.Password    = "******";
                    mq.VirtualHost = "/";
                    mq.Port        = 5672;
                    mq.HostName    = rabbitmqConnectionString;
                });

                x.FailedRetryCount    = 2;
                x.FailedRetryInterval = 60 * 5;


                x.FailedThresholdCallback = (m) =>
                {
                    Log.Error($@"事件总线处理失败:A message of type {m.MessageType} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {m.Message.GetName()}, id: {m.Message.GetId()}, value: {m.Message.Value.ToJson()}");
                };

                x.UseDashboard();

                x.Version = capBusOptions.VersionName;

                x.ConsumerThreadCount = 1;
            });

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            return(iocProvider.Item1);
        }
Пример #8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();


            services.AddHttpClient();
            services.AddHttpClient("monitor");
            services.AddHealthChecks().AddCheck <RandomHealthCheck>("random");


            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Warning);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            // token
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            services.AddAuthentication();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("IdentityServer"),
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = signingKey,
                    ValidateLifetime         = false
                };

                // WebSocket的Token来自QueryString
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken))
                        {
                            context.Request.Query.TryGetValue("token", out accessToken);
                        }

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            //.AddIdentityServerAuthentication( options =>
            //{
            //    options.Authority = Configuration.GetValue<string>( "IdentityServer" );
            //    options.RequireHttpsMetadata = false;// 指定是否为HTTPS

            //    options.ApiName = "api";

            //    // WebSocket的Token来自QueryString
            //    options.Events = new JwtBearerEvents {
            //        OnMessageReceived = context =>
            //        {
            //            var accessToken = context.Request.Query[ "access_token" ];
            //            if( string.IsNullOrEmpty( accessToken ) ) {
            //                context.Request.Query.TryGetValue( "token", out accessToken );
            //            }

            //            // If the request is for our hub...
            //            var path = context.HttpContext.Request.Path;
            //            if( !string.IsNullOrEmpty( accessToken ) && ( path.StartsWithSegments( "/hubs/" ) ) ) {
            //                // Read the token out of the query string
            //                context.Token = accessToken;
            //            }
            //            return Task.CompletedTask;
            //        }
            //    };
            //} );

            // permission
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policyBuilder =>
                {
                    policyBuilder.Requirements.Add(new PermissionRequirement());
                    policyBuilder.RequireAuthenticatedUser();
                });
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationPolicy>();

            // api doc
            services.AddSwaggerGen(c =>
            {
                // https://localhost:44312/swagger/v1/swagger.json
                c.SwaggerDoc("v1",
                             new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title       = "烽客 API",
                    Version     = "v1",
                    Description = "烽客 API 文档",
                });

                c.EnableAnnotations();

                //c.CustomOperationIds( e => $"{e.ActionDescriptor.RouteValues[ "action" ]}");
                c.CustomOperationIds(apiDesc =>
                {
                    return(apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
                var xmlPath2 = Path.Combine(AppContext.BaseDirectory, "Syinpo.Model.xml");
                if (File.Exists(xmlPath2))
                {
                    c.IncludeXmlComments(xmlPath2);
                }

                //
                c.DescribeAllEnumsAsStrings();

                //
                //c.AddFluentValidationRules();

                //http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/
                c.OperationFilter <AuthorizeCheckOperationFilter>();

                //c.AddSecurityDefinition( "oauth2", new OAuth2Scheme {
                //    Type = "oauth2",
                //    Flow = "implicit",
                //    AuthorizationUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/authorize",
                //    TokenUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/token",
                //    Scopes = new Dictionary<string, string>()
                //    {
                //        { "api", "Syinpo API" }
                //    }
                //} );
            });

            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddMemoryCache();
            //services.AddHostedService<CacheDamageWorker>();
            //services.AddHostedService<JieLongWorker>();
            services.AddHostedService <HealthCheckWorker>();


            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration        = cacheOptions.RedisConfiguration;
                options.InstanceName         = cacheOptions.RedisInstanceName;
                options.ConfigurationOptions = ConnectionOptions.Option;
            });
            services.AddDistributedMemoryCache();


            //signalr
            services.Configure <SqlBusOptions>(Configuration.GetSection("SqlBus"));
            var sqlBusOptions = Configuration.GetSection("SqlBus").Get <SqlBusOptions>();

            if (sqlBusOptions.UseSignalrRedis)
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                })
                .AddJsonProtocol()
                .AddStackExchangeRedis(cacheOptions.RedisConfiguration, options =>
                {
                    options.Configuration.ChannelPrefix = "SigRis";
                });
            }
            else
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                });
            }


            //signalrbus
            var sysOptions = Configuration.GetSection("Sys").Get <SysOptions>();

            if (sysOptions.SignalrBus.UserSignalrBus)
            {
                services.AddSignalrBus();
            }

            //hangfire
            services.Configure <HangfireOptions>(Configuration.GetSection("Hangfire"));
            var hangfireOptions = Configuration.GetSection("Hangfire").Get <HangfireOptions>();

            if (hangfireOptions.UseHangfire)
            {
                string taskConnectionString = Configuration.GetConnectionString("HangfireConnection");
                services.AddHangfire(x => x.UseSqlServerStorage(taskConnectionString));

                if (hangfireOptions.UseHangfireServer)
                {
                    services.AddHangfireServer();
                }

                JobStorage.Current = new SqlServerStorage(taskConnectionString);

                if (hangfireOptions.UseHangfireServer)
                {
                    HangfireRegister.Register();
                }
            }

            // Monitor
            services.Configure <MonitorOptions>(Configuration.GetSection("Monitor"));
            var monitorOptions = Configuration.GetSection("Monitor").Get <MonitorOptions>();

            services.AddSingleton <MonitorExporter>();
            services.AddOpenTelemetry((sp, builder) =>
            {
                builder.SetSampler(new AlwaysSampleSampler());
                builder.UseMonitor(sp).AddRequestCollector().AddDependencyCollector();
            });
            services.AddScoped(resolver => resolver.GetService <TracerFactory>().GetTracer("syinpo-api-tracer"));
            if (monitorOptions.UseMonitor)
            {
                services.AddHostedService <MonitorWorker>();
            }

            //数据保护
            services.AddDataProtection();
            services.Configure <PasswordHasherOptions>(option =>
            {
                option.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
            });
            services.AddSingleton <Syinpo.Core.EasyLicense.PartnerAuthenticationHelper>();

            // 服务总线
            services.Configure <CapBusOptions>(Configuration.GetSection("CapBus"));
            var capBusOptions = Configuration.GetSection("CapBus").Get <CapBusOptions>();

            services.AddCap(x =>
            {
                string capConnectionString = Configuration.GetConnectionString("CapConnection");
                x.UseSqlServer(capConnectionString);

                string rabbitmqConnectionString = capBusOptions.RabbitMQConnection;
                x.UseRabbitMQ(mq =>
                {
                    mq.UserName    = "******";
                    mq.Password    = "******";
                    mq.VirtualHost = "/";
                    mq.Port        = 5672;
                    mq.HostName    = rabbitmqConnectionString;
                });

                x.FailedRetryCount    = 2;
                x.FailedRetryInterval = 60 * 5;


                x.FailedThresholdCallback = (m) =>
                {
                    Log.Error($@"事件总线处理失败:A message of type {m.MessageType} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {m.Message.GetName()}, id: {m.Message.GetId()}, value: {m.Message.Value.ToJson()}");
                };

                x.UseDashboard();

                x.Version = capBusOptions.VersionName;

                x.ConsumerThreadCount = 1;
            });

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            // task
            if (hangfireOptions.UseHangfire)
            {
                GlobalConfiguration.Configuration.UseAutofacActivator(iocProvider.Item2, false);
            }

            //设置 Excel 帮助类为非商业版
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;



            return(iocProvider.Item1);
        }
Пример #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options => {
                //添加配置
                //权限验证
                options.Filters.Add <PermissionValidateFilter>();
            })
            #region asp.net core 2.0 默认返回的结果格式是Json, 并使用json.net对结果默认做了camel case的转化(大概可理解为首字母小写).  这一点与老.net web api 不一样, 原来的 asp.net web api 默认不适用任何NamingStrategy, 需要手动加上camelcase的转化. 如果非得把这个规则去掉, 那么就在configureServices里面改一下:
            .AddNewtonsoftJson(options =>
            {
                //日期处理 日期类型默认格式化处理
                options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
                options.SerializerSettings.DateFormatString   = "yyyy-MM-dd HH:mm:ss";

                //不更改元数据的key的大小写
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            })
            #endregion
            ;

            services.AddDbContext <LyAdminDbContext>(options =>
            {
                //配置:https://docs.microsoft.com/zh-cn/ef/core/logging-events-diagnostics/extensions-logging?tabs=v3
                //启用显示敏感数据
                options.EnableSensitiveDataLogging(true);
                //日志
                options.UseLoggerFactory(MyLoggerFactory);
                //详细查询异常
                options.EnableDetailedErrors();
                var connectionString = this.Configuration["ConnectionStrings:MySqlConn"];
                options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
            });

            #region AutoMapper
            services.AddAutoMapper(MapperRegister.MapType());
            #endregion

            #region 依赖注入
            //AddTransient:瞬时模式每次请求,都获取一个新的实例。即使同一个请求获取多次也会是不同的实例

            //AddScoped:每次请求,都获取一个新的实例。同一个请求获取多次会得到相同的实例

            //AddSingleton单例模式:每次都获取同一个实例
            #region 两种都可以
            //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpContextAccessor();
            #endregion
            #endregion

            services.AddJwtAuth();

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",                //版本
                    Title       = "Ly.Admin.API",      //标题
                    Description = "Ly.Admin.API 接口项目", //描述
                    Contact     = new OpenApiContact {
                        Name = "Jelly", Email = "", Url = new Uri("https://www.525600.xyz")
                    },
                    License = new OpenApiLicense {
                        Name = "License", Url = new Uri("https://www.525600.xyz")
                    }
                });
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); //获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                                                                                         //var basePath = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(basePath, "Ly.Admin.API.xml");                //这个是右键属性生成输出中配置的xml文件名
                                                                                         //c.IncludeXmlComments(xmlPath);//默认的第二个参数是false,对方法的注释
                c.IncludeXmlComments(xmlPath, true);                                     //这个是controller的注释
            });
            #endregion


            #region 配置直接获取 LY.Admin.Util\Configuration\LYAdminOptions.cs
            var lyAdminConfigOptions = File.ReadAllText("LYAdminConfig.options.json");
            var lyAdminOptionsRoot   = JsonConvert.DeserializeObject <LyAdminOptionsRoot>(lyAdminConfigOptions);
            if (lyAdminOptionsRoot == null)
            {
                throw new NullReferenceException("LYAdminConfig.options.json error");
            }
            GlobalSettings.LyAdminOptions = lyAdminOptionsRoot.LyAdminOptions;

            #endregion
        }
Пример #10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
            })
            .AddNewtonsoftJson()
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();
            services.AddHttpClient("monitor");

            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug )
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information )
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            // token
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            services.AddAuthentication();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("IdentityServer"),
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = signingKey,
                    ValidateLifetime         = false
                };

                // WebSocket的Token来自QueryString
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken))
                        {
                            context.Request.Query.TryGetValue("token", out accessToken);
                        }

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });


            // permission
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policyBuilder =>
                {
                    policyBuilder.Requirements.Add(new PermissionRequirement());
                    policyBuilder.RequireAuthenticatedUser();
                });
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationPolicy>();

            // cache
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheOptions.RedisConfiguration;
                options.InstanceName  = cacheOptions.RedisInstanceName;
            });
            services.AddDistributedMemoryCache();

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            return(iocProvider.Item1);
        }
Пример #11
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();

            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug )
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information )
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            //signalr
            services.AddSignalR(p =>
            {
                p.EnableDetailedErrors  = true;
                p.ClientTimeoutInterval = TimeSpan.FromSeconds(60);
                p.HandshakeTimeout      = TimeSpan.FromSeconds(30);
                p.KeepAliveInterval     = TimeSpan.FromSeconds(15);
            });

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            // token
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            services.AddAuthentication();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("IdentityServer"),
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = signingKey,
                    ValidateLifetime         = false
                };

                // WebSocket的Token来自QueryString
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken))
                        {
                            context.Request.Query.TryGetValue("token", out accessToken);
                        }

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            //.AddIdentityServerAuthentication( options =>
            //{
            //    options.Authority = Configuration.GetValue<string>( "IdentityServer" );
            //    options.RequireHttpsMetadata = false;// 指定是否为HTTPS

            //    options.ApiName = "api";

            //    // WebSocket的Token来自QueryString
            //    options.Events = new JwtBearerEvents {
            //        OnMessageReceived = context =>
            //        {
            //            var accessToken = context.Request.Query[ "access_token" ];
            //            if( string.IsNullOrEmpty( accessToken ) ) {
            //                context.Request.Query.TryGetValue( "token", out accessToken );
            //            }

            //            // If the request is for our hub...
            //            var path = context.HttpContext.Request.Path;
            //            if( !string.IsNullOrEmpty( accessToken ) && ( path.StartsWithSegments( "/hubs/" ) ) ) {
            //                // Read the token out of the query string
            //                context.Token = accessToken;
            //            }
            //            return Task.CompletedTask;
            //        }
            //    };
            //} );

            // permission
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policyBuilder =>
                {
                    policyBuilder.Requirements.Add(new PermissionRequirement());
                    policyBuilder.RequireAuthenticatedUser();
                });
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationPolicy>();

            // api doc
            services.AddSwaggerGen(c =>
            {
                // https://localhost:44312/swagger/v1/swagger.json
                c.SwaggerDoc("v1",
                             new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title       = "烽客 API",
                    Version     = "v1",
                    Description = "烽客 API 文档",
                });

                c.EnableAnnotations();

                //c.CustomOperationIds( e => $"{e.ActionDescriptor.RouteValues[ "action" ]}");
                c.CustomOperationIds(apiDesc =>
                {
                    return(apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
                var xmlPath2 = Path.Combine(AppContext.BaseDirectory, "Syinpo.Model.xml");
                if (File.Exists(xmlPath2))
                {
                    c.IncludeXmlComments(xmlPath2);
                }

                //
                c.DescribeAllEnumsAsStrings();

                //
                //c.AddFluentValidationRules();

                //http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/
                c.OperationFilter <AuthorizeCheckOperationFilter>();

                //c.AddSecurityDefinition( "oauth2", new OAuth2Scheme {
                //    Type = "oauth2",
                //    Flow = "implicit",
                //    AuthorizationUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/authorize",
                //    TokenUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/token",
                //    Scopes = new Dictionary<string, string>()
                //    {
                //        { "api", "Syinpo API" }
                //    }
                //} );
            });

            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddMemoryCache();

            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheOptions.RedisConfiguration;
                options.InstanceName  = cacheOptions.RedisInstanceName;
            });
            services.AddDistributedMemoryCache();


            //hangfire
            services.Configure <HangfireOptions>(Configuration.GetSection("Hangfire"));
            var hangfireOptions = Configuration.GetSection("Hangfire").Get <HangfireOptions>();


            // task
            if (hangfireOptions.UseHangfire)
            {
                string taskConnectionString = Configuration.GetConnectionString("HangfireConnection");
                services.AddHangfire(x => x.UseSqlServerStorage(taskConnectionString));
                services.AddHangfireServer();
                JobStorage.Current = new SqlServerStorage(taskConnectionString);
                HangfireRegister.Register();
            }

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            // task
            if (hangfireOptions.UseHangfire)
            {
                GlobalConfiguration.Configuration.UseAutofacActivator(iocProvider.Item2, false);
            }

            return(iocProvider.Item1);
        }
Пример #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
            }).AddControllersAsServices();

            // tokenClient
            services.AddHttpClient();
            services.AddHttpClient("token_client",
                                   client => client.BaseAddress = new Uri($"{CommonHelper.GetWebLocation()}connect/token"));

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Debug);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             .CreateLogger();
            }

            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 授权服务器
            // http://192.168.50.58:6060/.well-known/openid-configuration
            AddIdentityServer(services);

            //services.AddAuthentication();
            //services.AddAuthentication( "Bearer" )
            //    .AddIdentityServerAuthentication( options =>
            //    {
            //        options.Authority = "https://localhost:44372";
            //        options.RequireHttpsMetadata = false;

            //        options.ApiName = "api";
            //    } );

            // cache
            services.AddDistributedMemoryCache();

            // 请求限制
            services.AddMemoryCache();

            // IoC & DI
            services.AddAutofac();

            var serviceProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(serviceProvider.Item1, serviceProvider.Item2);
            return(serviceProvider.Item1);
        }