private void AddCorsService(IServiceCollection services, WebApiOption config) { //添加cors 服务 services.AddCors(options => options.AddPolicy(WebApiOption.CORS_POLICY_NAME, p => p.WithOrigins(config.Cors.Original) .AllowAnyMethod().AllowAnyHeader())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc() //序列化设置 .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key //options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd hh-MM-ss"; } ); services.AddOptions(); services.Configure <WebApiOption>(Configuration.GetSection("WebAPI")); IServiceProvider serviceProvider = services.BuildServiceProvider(); //获取配置 WebApiOption config = serviceProvider.GetService <IOptions <WebApiOption> >().Value; AddCorsService(services, config); AddDBService(services, config); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() //序列化设置 .AddNewtonsoftJson(options => { // 忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰 .net core默认使用驼峰 首字母小写 options.SerializerSettings.ContractResolver = new DefaultContractResolver(); // 设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 如字段为null值,该字段不会返回到前端 // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); //services.AddOptions(); //.net core 3.0不需要添 services.Configure <WebApiOption>(Configuration.GetSection("WebAPI")); //此种方法将属性注入DI,可以用IOptions<WebApiOption> option取值 //获取配置 //方法1 WebApiOption config = Configuration.GetSection("WebAPI").Get<WebApiOption>(); //方法2 IServiceProvider serviceProvider = services.BuildServiceProvider(); WebApiOption config = serviceProvider.GetService <IOptions <WebApiOption> >().Value; AddDBService(services, config); AddCorsService(services, config); }
private void AddDBService(IServiceCollection services, WebApiOption config) { //数据库上下文全局设置 services.AddSingleton <IDapperContext>(_ => new DapperContext(config)); services.AddScoped <IDepartmentRep, DepartmentRep>(); services.AddScoped <IDepartmentService, DepartmentService>(); }
public DapperContext(WebApiOption config) { m_Config = config; }