示例#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
        /// <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());
        }
示例#4
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;
            });
        }
示例#5
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
        }