コード例 #1
0
ファイル: Startup.cs プロジェクト: cxyzgl/ABPFramework
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //使程序支持GBK,gb2312
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            services.AddHttpClient();

            services.AddMvc();

            var corsOrigins = _appConfiguration["App:CorsOrigins"]
                              .Split(",", StringSplitOptions.RemoveEmptyEntries)
                              .Select(o => o.RemovePostFix("/"))
                              .ToArray();

            services.AddCors(options =>
            {
                options.AddPolicy(_defaultCorsPolicyName,
                                  builder => builder.WithOrigins(corsOrigins)
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials());
            });

            services.AddCors(c =>
            {
                c.AddPolicy(_allowAnyOriginCorsPolicyName, policy =>
                {
                    policy.AllowAnyOrigin() //允许任何源
                    .AllowAnyMethod()       //允许任何方式
                    .AllowAnyHeader()       //允许任何头
                    .AllowCredentials();    //允许cookie
                });
            });

            services.AddJwtAuthentication(option =>
            {
                option.Audience               = _audience;
                option.ValidateAudience       = true;
                option.Issuer                 = _issuer;
                option.ValidateIssuer         = true;
                option.SecurityAlgorithms     = SecurityAlgorithms.HmacSha256;
                option.SigningKey             = _jwt_secret;
                option.ValidMinutes           = _validMinutes;
                option.OnChallenge            = context => JwtOptionsCallBack.OnChallenge(context);
                option.OnAuthenticationFailed = context => JwtOptionsCallBack.OnAuthenticationFailed(context);
                option.OnTokenValidated       = context => JwtOptionsCallBack.OnTokenValidated(context);
                option.SecurityTokenValidator = new JwtCustomValidator();
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("WebApi", new Info {
                    Title = "ApiDoc", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Description = "请输入OAuth接口返回的Token,前置Bearer。示例:Bearer {Token}",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() }
                });
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <CJSWebApiModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config"));

                //解决属性依赖注入报错
                var propInjector = options.IocManager.IocContainer.Kernel.ComponentModelBuilder
                                   .Contributors.OfType <PropertiesDependenciesModelInspector>().Single();
                options.IocManager.IocContainer.Kernel.ComponentModelBuilder.RemoveContributor(propInjector);
                options.IocManager.IocContainer.Kernel.ComponentModelBuilder.AddContributor(new AbpPropertiesDependenciesModelInspector(new DefaultConversionManager()));
            }));
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: tusubasa46/ABPFramework
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddWebApiServices(_env);

            var corsOrigins = _appConfiguration["App:CorsOrigins"]
                              .Split(",", StringSplitOptions.RemoveEmptyEntries)
                              .Select(o => o.RemovePostFix("/"))
                              .ToArray();

            services.AddCors(options =>
            {
                options.AddPolicy(_defaultCorsPolicyName,
                                  builder => builder.WithOrigins(corsOrigins)
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials());
            });

            services.AddCors(c =>
            {
                c.AddPolicy(_allowAnyOriginCorsPolicyName, policy =>
                {
                    policy.AllowAnyOrigin() //允许任何源
                    .AllowAnyMethod()       //允许任何方式
                    .AllowAnyHeader()       //允许任何头
                    .AllowCredentials();    //允许cookie
                });
            });

            services.AddJwtAuthentication(option =>
            {
                option.Audience               = _jwtBearerConfig.Audience;
                option.ValidateAudience       = true;
                option.Issuer                 = _jwtBearerConfig.Issuer;
                option.ValidateIssuer         = true;
                option.SecurityAlgorithms     = SecurityAlgorithms.HmacSha256;
                option.SigningKey             = _jwtBearerConfig.PrivateKeys;
                option.ValidMinutes           = _jwtBearerConfig.ValidMinutes;
                option.OnChallenge            = context => JwtOptionsCallBack.OnChallenge(context);
                option.OnAuthenticationFailed = context => JwtOptionsCallBack.OnAuthenticationFailed(context);
                option.OnTokenValidated       = context => JwtOptionsCallBack.OnTokenValidated(context);
                option.SecurityTokenValidator = new JwtCustomValidator();
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("WebApi", new Info {
                    Title = "ApiDoc", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Description = "请输入OAuth接口返回的Token,前置Bearer。示例:Bearer {Token}",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() }
                });
                options.DocumentFilter <EnumDescriptionDocumentFilter>();
                //options.SchemaRegistryOptions.CustomTypeMappings.Add(typeof(IFormFile), () => new Schema() { Type = "file", Format = "binary" });
                options.OperationFilter <FormFileOperationFilter>();
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "CXY.CJS.Application.xml");
                options.IncludeXmlComments(xmlPath);
                xmlPath = Path.Combine(basePath, "CXY.CJS.Core.xml");
                options.IncludeXmlComments(xmlPath);
            });

            services.AddSingleton(_jwtBearerConfig);

            //// 配置邮件发送
            //var mailSendConfig = _appConfiguration.GetSection("SystemSmtpSenderConfiguration").Get<SystemSmtpSenderConfiguration>();
            //services.AddSystemSmtpSender(mailSendConfig);

            //配置短信发送
            //services.AddSmsSender(_appConfiguration.GetSection("SmsSenderConfiguration").Get<SmsSenderConfiguration>());

            services.Configure <ApiUrlConfig>(_appConfiguration.GetSection("ApiUrlConfig"));

            // Configure Abp and Dependency Injection
            return(services.AddAbp <CJSWebApiModule>(options =>
            {
                //Serilog日志注入
                var configBuilder = new LoggerConfiguration();
                configBuilder = configBuilder.ReadFrom.Configuration(_appConfiguration);
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(logger => logger.LogUsing(new SerilogFactory(configBuilder.CreateLogger())));

                //解决属性依赖注入报错
                var propInjector = options.IocManager.IocContainer.Kernel.ComponentModelBuilder
                                   .Contributors.OfType <PropertiesDependenciesModelInspector>().Single();
                options.IocManager.IocContainer.Kernel.ComponentModelBuilder.RemoveContributor(propInjector);
                options.IocManager.IocContainer.Kernel.ComponentModelBuilder.AddContributor(new AbpPropertiesDependenciesModelInspector(new DefaultConversionManager()));
            }));
        }