Example #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //跨域设置
            services.AddCors(options =>
                             options.AddPolicy("cors",
                                               builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials())
                             );

            //数据库上下文配置
            DbContextConfig.DoConfig(services, Configuration["Root:Database:ConnectionString"]);

            //配置身份服务器与内存中的存储,密钥,客户端和资源
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityServer4Resources.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServer4Resources.GetApiResources())
            .AddInMemoryClients(IdentityServer4Resources.GetClients())
            .AddResourceOwnerValidator <LoginValidator>()       //添加自定义验证类
            .AddProfileService <ProfileService>();

            services.AddAuthentication("Bearer")                        //添加授权模式
            .AddIdentityServerAuthentication(Options => {
                Options.Authority            = "http://localhost:5000"; //授权服务器地址
                Options.RequireHttpsMetadata = false;                   //没有证书,不启用https
                Options.ApiName = "api";                                //指定ApiName与Config配置中的相同
            });

            //添加Mvc服务到DI容器
            services.AddMvc();
            //添加跨域服务到DI容器
            services.AddCors();
            //将Options注入到DI容器
            services.AddOptions();
            services.Configure <AppsettingDataModel>(Configuration.GetSection("Root"));
            //Http请求访问器注入到DI容器
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSignalR();

            //业务逻辑注入到DI容器
            IocConfig.DoDependencyInjection(services);

            //创建Redis单例实例
            //RedisConfig.CreateInstance(Configuration["Root:Redis:Host"], Configuration["Root:Redis:PreKey"]);
        }