Ejemplo n.º 1
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
                options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
            }
                )
            .AddRazorRuntimeCompilation()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddScoped <IWebResourceManager, WebResourceManager>();

            services.AddSignalR();

            // Configure Abp and Dependency Injection
            return(services.AddAbp <ametyevo - villageWebMvcModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig(
                               _hostingEnvironment.IsDevelopment()
                            ? "log4net.config"
                            : "log4net.Production.config"
                               )
                           )
                       ));
        }
Ejemplo n.º 2
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest).AddNewtonsoftJson();

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters        = true;
                options.SuppressModelStateInvalidFilter = true;
            });

            //IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "FacadeProjectName API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                var types = new Type[]
                {
                    typeof(FacadeProjectNameWebHostModule),
                    typeof(FacadeProjectNameApplicationModule),
                    typeof(FacadeProjectNameDomainServiceModule),
                    typeof(FacadeProjectNameDomainServiceShareModule),
                    typeof(FacadeProjectNameOracleModule),
                };
                foreach (var t in types)
                {
                    var xmlFile = $"{t.GetAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    options.IncludeXmlComments(xmlPath, true);
                }
            });

            // Configure Abp and Dependency Injection
            return(services.AddFacade <FacadeProjectNameWebHostModule>(
                       // Configure Log4Net logging
                       options =>
            {
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(f =>
                {
                    f.UseFacadeNLog($"{_env.ContentRootPath}\\NLog.config");
                    //f.UseFacadeNLog($"{_env.ContentRootPath}\\NLog.config",_appConfiguration["Exceptionless:ServerUrl"], _appConfiguration["Exceptionless:ApiKey"]);
                });
            }));
        }
Ejemplo n.º 3
0
        public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
                if (_corsEnabled)
                {
                    options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
                }
            });

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);
            services.AddScoped <IWebResourceManager, WebResourceManager>();
            services.AddSingleton <IMigrationManager>(new MigrationManager());
            services.AddSingleton <IWebConfig>(new WebConfig());

            // Configure CORS for angular2 UI or other clients. This does not activate Cors. It only configures it.
            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    //App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
                    builder
                    .WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.Trim().RemovePostFix("/")).ToArray())
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            //Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            if (_swaggerEnabled)
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Info {
                        Title = "OpenApp API", Version = "v1"
                    });
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(x => x.FullName);
                    // Define the BearerAuth scheme that's in use
                    options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                    {
                        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                        Name        = "Authorization",
                        In          = "header",
                        Type        = "apiKey"
                    });
                    // Assign scope requirements to operations based on AuthorizeAttribute
                    options.OperationFilter <SecurityRequirementsOperationFilter>();
                });
            }

            AddAdditionalServices(services);

            //Configure Abp and Dependency Injection
            return(services.AddAbp <TModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );
            }));
        }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
            }
                ).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("192.168.1.43"));
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });


            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddAntiforgery();

            services.AddMvc(options =>
            {
                //var policy = new AuthorizationPolicyBuilder()
                //         .RequireAuthenticatedUser()
                //         .Build();
                //options.Filters.Add(new AuthorizeFilter(policy));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("xml", MediaTypeHeaderValue.Parse("application/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("config", MediaTypeHeaderValue.Parse("application/xml"));
                options.FormatterMappings.SetMediaTypeMappingForFormat
                    ("js", MediaTypeHeaderValue.Parse("application/json"));
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                options.ModelBinderProviders.Add(new ArrayModelBinderProvider());
                options.ModelBinderProviders.Add(new CollectionModelBinderProvider());

                options.ValueProviderFactories.Add(new JQueryQueryStringValueProviderFactory());
                //options.ValueProviderFactories.Add(new CookieValueProviderFactory());
                options.ModelMetadataDetailsProviders.Add(
                    new ExcludeBindingMetadataProvider(typeof(System.Version)));
                options.ModelMetadataDetailsProviders.Add(
                    new SuppressChildValidationMetadataProvider(typeof(System.Guid)));
                //options.Conventions.Add(new RouteTokenTransformerConvention(
                //    new SlugifyParameterTransformer()));
            })
            .AddXmlDataContractSerializerFormatters()
            .AddXmlSerializerFormatters()
            .AddDataAnnotationsLocalization(options =>
            {
                //options.DataAnnotationLocalizerProvider = (type, factory) =>
                //    factory.Create(typeof(SharedResource));
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);


            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr")
                };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
                options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
                {
                    // My custom request culture logic
                    return(new ProviderCultureResult("en"));
                }));
            });
            services.AddResponseCaching();
            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromDays(30);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            services.AddRouting(options =>

                                options.LowercaseUrls = true
                                );
            services.AddDistributedMemoryCache(options =>
            {
            });

            services.AddDistributedSqlServerCache(options =>
            {
                options.ConnectionString = "Server=localhost; Database=IntuitDb;User Id=US;Password=Bg-15rzbb; Trusted_Connection=True;";
                options.SchemaName       = "dbo";
                options.TableName        = "TestCache";
            });
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
            });

            services.Configure <CookieTempDataProviderOptions>(options =>
            {
                options.Cookie.IsEssential = true;
            });

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost";
                options.InstanceName  = "SampleInstance";
            });

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <BrotliCompressionProvider>();
                options.Providers.Add <GzipCompressionProvider>();
                //options.Providers.Add<CustomCompressionProvider>();
                options.MimeTypes =
                    ResponseCompressionDefaults.MimeTypes.Concat(
                        new[] { "image/svg+xml" });
            });
            //AuthConfigurer.Configure(services, Configuration);
            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                                          UnicodeRanges.CjkUnifiedIdeographs }));
            services.Configure <BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure <IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
                options.ForwardClientCertificate = false;
            });
            services.Configure <IISServerOptions>(options =>
            {
                options.AutomaticAuthentication = false;
            });
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");


            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "Intuit API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <IntuitWebHostModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig("log4net.config")
                           )
                       ));
        }
Ejemplo n.º 5
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(
                options => options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName))
                );

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "DotNetRu API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                // Assign scope requirements to operations based on AuthorizeAttribute
                options.OperationFilter <SecurityRequirementsOperationFilter>();
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <DotNetRuWebHostModule>(
                       // Configure Log4Net logging
                       options =>
            {
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );
                options.PlugInSources.AddFolder(@"c:\SpbDotNet\_snippets\Demo2\Plugin");
            }
                       ));
        }
Ejemplo n.º 6
0
        public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
                if (_corsEnabled)
                {
                    options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
                }
            });

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);
            services.AddScoped <IWebResourceManager, WebResourceManager>();
            services.AddSingleton <IMigrationManager>(new MigrationManager());
            services.AddSingleton <IWebConfig>(new WebConfig());

            // Configure CORS for angular2 UI or other clients. This does not activate Cors. It only configures it.
            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    //App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
                    builder
                    .WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.Trim().RemovePostFix("/")).ToArray())
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            //Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            if (_swaggerEnabled)
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Info {
                        Title = "OpenApp API", Version = "v1"
                    });
                    options.DocInclusionPredicate((docName, description) => true);

                    /*
                     * Explanation of code bellow concerning CustomSchemaId
                     *
                     * Swashbuckle for .Net Core generates simple DTO names by default. This is good and readable, but can become a problem when there are multiple DTO's with the same name in different Namespaces.
                     *
                     * Thus, a more robust approach is to generate a FullName. This includes namespace, assembly version, etc, etc.
                     * Another problem is that when returning a DTO with generics. Like, for example, PagedResultDto<LanguageDto> a weird name is generated, including a backtick.
                     * This weird syntax
                     *  1. Is not very readable
                     *  2. Breaks code generation in later stages (for e.g. TypeScript)
                     *
                     * We run into this issue when using CrudAppService. To fix this we apply a simple replace of the weird syntax characters to produce a Swagger definition that can be used for CodeGen.
                     *
                     * A problem with the FullName is that it generates very long and unreadable names, since it includes version number of the assembly, etc, etc
                     * To get around this we provide an alternative where we only include Namespace, TypeName and generics. This approach seems to work for now, but might break in untested edge cases.
                     *
                     * In any case FullName doesn't seem robust anyway whenever using generics, so it is hard to rely on FullName as a robust solution overall and it seems reasonable that our implementation is simply better.
                     *
                     * A case in which the current implementation might break would be with more than 1 generic. This, however, is not the case with CrudAppService and thus should only be adjusted when there is a use case for multiple generics.
                     * This use case could very well be in a user's project. Whenever someone runs into this problem, a fix should be pushed to OpenApp.
                     */

                    //options.CustomSchemaIds(x => x.FullName); /* Using FullName */
                    //options.CustomSchemaIds(t => t.FullName.Replace("`1", "")); /* Using FullName with fix for Generics (only 1) */

                    options.CustomSchemaIds(type => CreateTypeNameWithNameSpace(type)); /* Custom naming implementation to support generics and multiple DTO's with the same name in different namespaces */


                    // Define the BearerAuth scheme that's in use
                    options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                    {
                        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                        Name        = "Authorization",
                        In          = "header",
                        Type        = "apiKey"
                    });

                    // Assign scope requirements to operations based on AuthorizeAttribute
                    options.OperationFilter <SecurityRequirementsOperationFilter>();

                    // By default ABP wraps API Responses with AjaxResponse. These don't get picked up automatically, so add them by enabling this OperationFilter.
                    // IMPORTANT: Should run after SecurityRequirementsOperationFilter. Otherwise the response type for alternative error codes will be incorrect.
                    options.OperationFilter <WrapAjaxResponseOperationFilter>();
                });
            }

            AddAdditionalServices(services);

            //Configure Abp and Dependency Injection
            return(services.AddAbp <TModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );
            }));
        }
Ejemplo n.º 7
0
        public static IServiceCollection AddTwinkle(this IServiceCollection services, IConfigurationRoot config, IList <IFilterMetadata> filters = null)
        {
            TwinkleContext.ServiceCollection = services;

            #region 添加http上下文服务
            services.AddHttpContextAccessor();
            #endregion

            #region 添加缓存服务
            switch (config.GetValue <string>("CacheStrategy"))
            {
            case "Redis":
                services.AddDistributedRedisCache(options =>
                {
                    options.Configuration = config.GetValue <string>("Redis:ServerHosts").Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
                    options.InstanceName  = config.GetValue <string>("Redis:ServerName");
                });

                services.AddSingleton(typeof(RedisService), (_) =>
                {
                    return(new RedisService(new RedisConfig
                    {
                        Password = config.GetValue <string>("Redis:Password"),
                        SentinelHosts = config.GetValue <string>("Redis:SentinelHosts").Split(',', StringSplitOptions.RemoveEmptyEntries),
                        ServerHosts = config.GetValue <string>("Redis:ServerHosts").Split(',', StringSplitOptions.RemoveEmptyEntries),
                        ServerName = config.GetValue <string>("Redis:ServerName")
                    }));
                });
                break;

            default:
                services.AddDistributedMemoryCache();
                break;
            }
            services.AddSingleton(typeof(ICacheService), typeof(CacheService));
            #endregion

            #region 添加身份认证服务
            AuthConfigurer.Configure(services, config);
            #endregion

            #region 添加Mvc服务
            services.AddMvc(options =>
            {
                //加载自定义Model绑定
                options.ModelBinderProviders.Insert(0, new TwinkleModelBinderProvider());
                //加载拦截器
                if (filters != null)
                {
                    foreach (var filter in filters)
                    {
                        options.Filters.Add(filter);
                    }
                }
            }).AddJsonOptions(options =>
            {   //序列化json格式时候,大写的首字母不自动转为小写
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                options.SerializerSettings.Formatting       = Newtonsoft.Json.Formatting.Indented;
            });
            #endregion

            #region 添加Session服务
            services.AddSession();
            #endregion

            #region 添加跨域支持服务
            if (config.GetValue <bool>("Cors:Enable"))
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("any", builder =>
                    {
                        builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();//指定处理cookie,客户端跨域访问时 需要 设置 xhrFields: {withCredentials: true}
                    });
                });
            }
            #endregion

            #region 添加SignalR服务
            services.AddSingleton(typeof(IOnlineClientManager), typeof(OnlineClientManager));
            services.AddSingleton(typeof(IRealTimeNotifier), typeof(SignalRRealTimeNotifier));

            services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            }).AddJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            });
            #endregion

            #region 取消Form文件上传大小限制
            services.Configure <FormOptions>(options =>
            {
                options.ValueLengthLimit         = int.MaxValue;
                options.MultipartBodyLengthLimit = int.MaxValue;
            });
            #endregion

            #region 设置字符集
            //设置字符集
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            #endregion

            #region 添加数据库操作
            services.AddScoped <DatabaseManager>();
            #endregion

            return(services);
        }
Ejemplo n.º 8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
            }
                ).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });



            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "FE-practice API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <FE - practiceWebHostModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig("log4net.config")
                           )
                       ));
        }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add services used for the workflows runtime.
            services.AddElsa(elsa => elsa.AddEntityFrameworkStores <SqlServerContext>(options => options.UseSqlServer(_appConfiguration.GetConnectionString("Elsa"))));
            services.AddHttpActivities(options => options.Bind(_appConfiguration.GetSection("Elsa:Http")));
            services.AddEmailActivities(options => options.Bind(_appConfiguration.GetSection("Elsa:Smtp")));
            services.AddTimerActivities(options => options.Bind(_appConfiguration.GetSection("Elsa:Timers")));

            // Add services used for the workflows dashboard.
            services.AddElsaDashboard();

            //MVC
            services.AddControllersWithViews(
                options =>
            {
                options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
            }
                ).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });



            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            services.AddSignalR();

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(_apiVersion, new OpenApiInfo
                {
                    Version     = _apiVersion,
                    Title       = "ElsaProject API",
                    Description = "ElsaProject",
                    // uncomment if needed TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name  = "ElsaProject",
                        Email = string.Empty,
                        Url   = new Uri("https://twitter.com/aspboilerplate"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "MIT License",
                        Url  = new Uri("https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/LICENSE"),
                    }
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
            });

            // Configure Abp and Dependency Injection
            return(services.AddAbp <ElsaProjectWebHostModule>(
                       // Configure Log4Net logging
                       options => options.IocManager.IocContainer.AddFacility <LoggingFacility>(
                           f => f.UseAbpLog4Net().WithConfig("log4net.config")
                           )
                       ));
        }
Ejemplo n.º 10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(
                options => options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName))
                );

            //IdentityRegistrar.Register(services);

            #region
            //start add by jjie   LogInManager  IUserClaimsPrincipalFactory
            ////services.AddLogging();
            ////services.AddScoped<LogInManager>();

            ////AbpIdentityBuilder identityBuilder = new AbpIdentityBuilder(services.AddIdentity<UserInfo, RoleInfo>(null), typeof(Tenant));
            ////var type = typeof(LogInManager);
            ////identityBuilder.Services.AddScoped<LogInManager>();
            ////identityBuilder.Services.AddScoped(typeof(LogInManager));

            //var identityBuilder = IdentityRegistrar.AddIdentity<UserInfo, RoleInfo>(services, options =>
            //{
            //    //options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie";
            //    //options.Cookies.ApplicationCookie.CookieName = "Interop";
            //});
            //identityBuilder.Services.AddScoped<LogInManager>();
            //identityBuilder.AddDefaultTokenProviders();

            services.AddScoped <LogInManager>();
            //end
            #endregion

            AuthConfigurer.Configure(services, _appConfiguration);

            //#if FEATURE_SIGNALR_ASPNETCORE
            //            services.AddSignalR();
            //#endif

            // Configure CORS for angular2 UI
            services.AddCors(
                options => options.AddPolicy(
                    _defaultCorsPolicyName,
                    builder => builder
                    .WithOrigins(
                        //App: CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    )
                );

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "zyGIS API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                // Assign scope requirements to operations based on AuthorizeAttribute
                options.OperationFilter <SecurityRequirementsOperationFilter>();
            });

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