依赖注入
由容器统一创建对象并管理其创建对象的生命周期;
AddTransient瞬时服务
每次使用都会创建新的实例
AddScoped作用域
容器或子容器的生命周期内,对象保持一致,如果容器释放掉,那就意味着对象也会释放掉;
AddSingleton单例
整个根容器的生命周期内是同一个对象
其他
TryAddScoped
AddHttpClient
AddHttpContextAccessor
AddDbContext
AddControllers
批量注入
其他生命周期中获取服务
中间件
系统自带
UseHttpsRedirection:强制https跳转
....
用途:
1全局拦截,如:IP白名单,请求头过滤
2错误处理,如:未处理异常处理、自定义异常(登录失败,参数错误等)处理
3权限校验
4。。。
配置文件application.json
读取方式:
1Configuration["A"]
2Configuration["A:b"]
3Configuration.GetValue<int>("A")
4Configuration.GetConnectionString
5Configuration.Get<TOption>
选项模式
IOptions、IOptionsMonitor以及IOptionsSnapshot的区别
配置项目启动地址
1修改launchSettings.json
2builder.WebHost.UseUrls("http://0.0.0.0:5552", "https://127.0.0.1:5553", "https://localhost:5554")
WebApi
ActionResult返回类型
return result;
return Ok(result);//200
return BadRequest(result);/400
CORS允许跨域请求
每次使用都会创建新的实例
容器或子容器的生命周期内,对象保持一致,如果容器释放掉,那就意味着对象也会释放掉;
整个根容器的生命周期内是同一个对象
TryAddScoped
AddHttpClient
AddHttpContextAccessor
AddDbContext
AddControllers
批量注入
var assembly = Assembly.GetExecutingAssembly(); var ilist = assembly.GetTypes().Where(t => t.GetTypeInfo().IsInterface); var list = assembly.GetTypes().Where(t => t.GetTypeInfo().IsClass); foreach (Type serviceType in list) { var interfaceType = ilist.FirstOrDefault(x => x.IsAssignableFrom(serviceType)); if (interfaceType != null) { if (interfaceType.FullName != null && interfaceType.FullName.StartsWith("KKBM.Application.Queries")) { services.AddScoped(interfaceType, serviceType); } } }
UseHttpsRedirection:强制https跳转
....
1全局拦截,如:IP白名单,请求头过滤
2错误处理,如:未处理异常处理、自定义异常(登录失败,参数错误等)处理
3权限校验
4。。。
1Configuration["A"]
2Configuration["A:b"]
3Configuration.GetValue<int>("A")
4Configuration.GetConnectionString
5Configuration.Get<TOption>
1修改launchSettings.json
2builder.WebHost.UseUrls("http://0.0.0.0:5552", "https://127.0.0.1:5553", "https://localhost:5554")
return result;
return Ok(result);//200
return BadRequest(result);/400
浙公网安备 33010602011771号