Beispiel #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 数据库连接字符串
            var srtdataBaseType = Configuration.GetConnectionString("DataBaseType");
            var strConnection   = Configuration.GetConnectionString("ConnectionString");

            //注入数据访问对象
            switch (Enum.Parse(typeof(DataBaseType), srtdataBaseType))
            {
            case DataBaseType.SqlServer:
                services.AddDbContext <Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseSqlServer(strConnection, b => b.UseRowNumberForPaging()),
                                                                             ServiceLifetime.Scoped);
                services.AddScoped <IDbConnection, SqlConnection>(t => new SqlConnection(strConnection));
                break;

            case DataBaseType.MySql:
                services.AddDbContext <Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseMySql(strConnection),
                                                                             ServiceLifetime.Scoped);
                services.AddScoped <IDbConnection, MySqlConnection>(t => new MySqlConnection(strConnection));
                break;
            }
            services.AddMvc(o =>
            {
                // 注册全局异常过滤器
                o.Filters.Add <HttpGlobalExceptionFilter>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
            //配置跨域
            services.AddCors(options => options.AddPolicy("blogWebApiServiceCors", builder =>
                                                          builder.AllowAnyOrigin().
                                                          AllowAnyMethod().
                                                          AllowAnyHeader())
                             );
            //权限验证
            services.AddAuthentication((options) =>
            {
                options.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters();
                options.RequireHttpsMetadata      = false;
                options.Audience  = "Zhouli.BlogWebApi";                   //api范围
                options.Authority = Configuration["IdentityServerAdress"]; //IdentityServer地址
            });
            //.AddIdentityServerAuthentication(options =>
            //    {
            //        options.Authority = Configuration.GetSection("IdentityServerAdress").Value; // IdentityServer服务器地址
            //        options.ApiName = "Zhouli.FileService"; // 用于针对进行身份验证的API资源的名称
            //        options.Audience=""
            //        options.RequireHttpsMetadata = false; // 指定是否为HTTPS
            //    });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("Zhouli.BlogWebApi_v1", new Info
                {
                    Title       = "博客的api文档",
                    Version     = "v1",
                    Description = "博客的api文档",
                    //服务条款
                    TermsOfService = "None",
                    //作者信息
                    Contact = new Contact
                    {
                        Name  = "周黎",
                        Email = "*****@*****.**",
                        Url   = "http://blog.zhouli.info/"
                    }
                });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "Zhouli.BlogWebApi.xml");
                c.IncludeXmlComments(xmlPath);
                c.OperationFilter <AddAuthTokenHeaderParameter>();
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Bearer 授权 \"Authorization:     Bearer+空格+token\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.OperationFilter <AuthorizeCheckOperationFilter>(); // 添加IdentityServer4认证过滤
            });
            //初始化Dto与实体映射关系
            ZhouliDtoMapper.Initialize();
            //.net core 2.1时默认不注入HttpContextAccessor依赖注入关系,所以再此手动注册
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // services.AddScoped(typeof(WholeInjection));
            services.AddResolveAllTypes(new string[] { "Zhouli.DAL", "Zhouli.BLL" });
        }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 数据库连接字符串
            var srtdataBaseType = Configuration.GetConnectionString("DataBaseType");
            var strConnection   = Configuration.GetConnectionString("ConnectionString");

            #region 框架的配置关系
            //注入数据访问对象
            switch (Enum.Parse(typeof(DataBaseType), srtdataBaseType))
            {
            case DataBaseType.SqlServer:
                services.AddDbContext <Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseSqlServer(strConnection, b => b.UseRowNumberForPaging()),
                                                                             ServiceLifetime.Scoped);
                services.AddTransient <IDbConnection, SqlConnection>(t => new SqlConnection(strConnection));
                break;

            case DataBaseType.MySql:
                services.AddDbContext <Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseMySql(strConnection),
                                                                             ServiceLifetime.Scoped);
                services.AddTransient <IDbConnection, MySqlConnection>(t => new MySqlConnection(strConnection));
                break;
            }
            //添加session依赖
            services.AddSession();
            //.net core 2.1时默认不注入HttpContextAccessor依赖注入关系,所以再此手动注册
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //注入gzip压缩依赖
            services.AddResponseCompression();
            //注入Response 缓存依赖
            services.AddResponseCaching();
            //重置区域匹配路径规则
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.AreaViewLocationFormats.Clear();
                options.AreaViewLocationFormats.Add("/Areas/{2}Manager/Views/{1}/{0}.cshtml");
                options.AreaViewLocationFormats.Add("/Areas/{2}Manager/Views/Shared/{0}.cshtml");
                options.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });
            //MemoryCache缓存
            services.AddMemoryCache();
            services.AddHttpClient();
            //mvc框架
            services.AddMvc(o =>
            {
                //注册全局异常过滤器
                o.Filters.Add <HttpGlobalExceptionFilter>();
                //配置缓存信息
                o.CacheProfiles.Add("default", new Microsoft.AspNetCore.Mvc.CacheProfile
                {
                    Duration = 60 * 10,  // 10 分钟
                });
                o.CacheProfiles.Add("Hourly", new Microsoft.AspNetCore.Mvc.CacheProfile
                {
                    Duration = 60 * 60,  // 1 hour
                                         //Location = Microsoft.AspNetCore.Mvc.ResponseCacheLocation.Any,
                                         //NoStore = true,
                                         //VaryByHeader = "User-Agent",
                                         //VaryByQueryKeys = new string[] { "aaa" }
                });
            }).AddJsonOptions(o =>
            {
                o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                o.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
            #endregion
            #region 自定义的配置关系
            //注入全局依赖注入提供者类
            // services.AddScoped(typeof(WholeInjection));
            services.AddScoped <UserAccount>();
            services.AddResolveAllTypes(new string[] { "Zhouli.DAL", "Zhouli.BLL" });
            //初始化Dto与实体映射关系
            ZhouliDtoMapper.Initialize();
            //注入配置文件类
            services.AddOptions().Configure <CustomConfiguration>(Configuration.GetSection("CustomConfiguration"));
            #endregion
        }