对于像我这样没接触过core的人,坑还是比较多的,一些基础配置和以前差别很大,这里做下记录
一、Startup
1.注册服务
???????// This method gets called by the runtime. Use this method to add services to the container. ???????public void ConfigureServices(IServiceCollection services) ???????{ ???????????services.AddMvc(); ???????????// services.AddTransient<IUser, User>(); ???????????//services.AddSingleton<IUser>(new User()); ???????????services.AddSingleton<IUser, User>(); ????????????????????????//services.AddScoped<>();//作用域注入 ???????????services.AddMemoryCache(); //MemoryCache缓存注入 ???????}
2.配置HTTP请求管道
听起来很蒙,其实就是用于处理我们程序中的各种中间件,它必须接收一个IApplicationBuilder参数,我们可以手动补充IApplicationBuilder的Use扩展方法,将中间件加到Configure中,用于满足我们的需求。
// This method gets called by the runtime. Use this method to add services to the container. ???????public void ConfigureServices(IServiceCollection services) ???????{ ???????????services.AddMvc(); ???????} ???????// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. ???????public void Configure(IApplicationBuilder app, IHostingEnvironment env) ???????{ ???????????if (env.IsDevelopment()) ???????????{ ???????????????app.UseDeveloperExceptionPage(); ???????????????app.UseBrowserLink(); ???????????} ???????????else ???????????{ ???????????????app.UseExceptionHandler("/Home/Error"); ???????????} ???????????app.UseStaticFiles(); ???????????app.UseMvc(routes => ???????????{ ???????????????routes.MapRoute( ???????????????????name: "default", ???????????????????template: "{controller=Home}/{action=Index}/{id?}"); ???????????}); ???????}
3.自定义配置文件
类似于web.config
??????///IHostingEnvironment获取环境变量信息,没错就是获取环境变量 ???????public Startup(IHostingEnvironment env) ???????{ ???????????//这里创建ConfigurationBuilder,其作用就是加载Congfig等配置文件 ???????????var builder = new ConfigurationBuilder() ???????????????//env.ContentRootPath:获取当前项目的跟路径 ???????????????.SetBasePath(env.ContentRootPath) ???????????????//使用AddJsonFile方法把项目中的appsettings.json配置文件加载进来,后面的reloadOnChange顾名思义就是文件如果改动就重新加载 ???????????????.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) ???????????????.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) ???????????????.AddEnvironmentVariables(); ???????????????????????//这返回一个配置文件跟节点:IConfigurationRoot ???????????Configuration = builder.Build(); ???????}
二、使用日志
public class HomeController : Controller ???{ ???????public HomeController() ???????{ ???????????ILoggerFactory loggerFactory = new LoggerFactory().AddConsole().AddDebug(); ???????????_logger = loggerFactory.CreateLogger<HomeController>(); ???????????_logger.LogInformation("================"); ???????????_logger.LogInformation("LOGGER IS START"); ???????????_logger.LogInformation("================"); ???????}}
ASP.NET Core学习之二 菜鸟踩坑
原文地址:http://www.cnblogs.com/xcsn/p/7821549.html