zoukankan      html  css  js  c++  java
  • ASP.NET Core中Startup.cs介绍

     本项目使用的是 visual studio 2017.net core 2.1的版本。

     ASP.NET Core Web应用被创建后,项目中会产生两个文件:Program.cs、Startup.cs,程序中把Program.cs作为Web应用程序的入口,程序启动时会调用Startup.cs类。

     ASP.NET MVC、WebApi中 Global.asax、FilterConfig.cs 和 RouteConfig.cs等类都被Program.cs、Startup.cs取而代之。

    Startup.cs的作用是:在项目中用到的静态文件、管道、服务、日志、路由、数据库连接、过滤器的注册等所有有关程序运行时使用。

    项目Startup.cs类:

    public class Startup
        {
            public IConfiguration Configuration { get; }
    
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<AppDbContext>(options => 
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                );
    
                services.AddMvc();
                //自动添加服务依赖
                //AddTransient 每次注册服务,会创建新的仓库,以保证仓库之间独立 
                //仓库依赖注入系统
                services.AddTransient<INoodleRepository, NoodleRepository>(); 
                services.AddTransient<IFeedbackRepository,FeedbackRepository>();
            }
    
            // 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.UseMvcWithDefaultRoute();  默认路由
    
                app.UseStaticFiles();
    
                app.UseAuthentication();
    
                app.UseMvc(route => 
                {
                    route.MapRoute("default","{controller=Home}/{action=Index}/{id?}");
                });
    
                app.Run(async (context) =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            }
        }

    从上面可以看出Startup.cs主要包含两个方法:ConfigureServices、Configure

    1.ConfigureServices方法:将服务注册到容器。eg:第三方组件

       services.AddMvc();   //注入MVC模块,包含MvcCore和常用的第三方库的服务和方法

       services.AddTransient<INoodleRepository, NoodleRepository>();   //自动添加服务依赖。瞬时注入,每次都会创建一个新的对象,以保证对象之间的独立性

       services.AddSingleton<IStudentRepository,MockStudentRepository>();  //单例注入,创建的对象在所有的地方所有的请求会话创建的都是相同的

       services.AddScoped<IStudentRepository,MockStudentRepository>();   //作用域注入,创建的对象在同一个请求会话时是相同的

    2.Configure方法:配置Http请求管道。 eg:session、cookie

        HostingEnvironment.IsDevelopment();   //判断当前运行环境是否是 Microsoft,如果是则返回true。

                                                                   //如果要判断其他运行环境,比如 Linux,则使用 env.IsEnvironment("environmentname") environmentname为要验证的环境名称。

        app.UseStaticFiles();   //使用静态文件

        //使用MVC管道路径,可以在这个配置路由等操作

        app.UseMvc(route => 
        {
             route.MapRoute("default","{controller=Home}/{action=Index}/{id?}");
        });

    实战:

     1. .net core使用session:

        ConfigureServices方法: services.AddSession();    //注入session

        Configure方法:app.UseSession();

        Controller:   

        //[Route("[controller]/[action]")]
        public class HomeController : Controller
        {
            // GET: /<controller>/
            public IActionResult Index()
            {
                HttpContext.Session.SetString("code","123456");
    
                return View();
            }
    
            public String About()
            {
                ViewBag.Code = HttpContext.Session.GetSession("code");
                return View();
            }
        }

    2. .net core使用Cache:

         ConfigureServices方法: services.AddMemoryCache();   //注册缓存服务

         Controller:

        public class HomeController : Controller
        {
            private IMemoryCache _cache;
          
            public HomeController (IMemoryCache memoryCache )
            {
                  _cache = memoryCache ;
            }
        }

    设置缓存:  _cache.set("key","value");

    移除缓存: _cache.remove("key");

  • 相关阅读:
    反转链表
    linux shell 读取配置文件的一个例子
    python 笔记碎片
    工作笔记整理
    linux服务器之间文件互传
    工作软件收集
    linux同步时间
    利用linux的df和du命令查看文件和目录的内存占用
    windows常用快捷键
    SUSE 12 安装 python3.6
  • 原文地址:https://www.cnblogs.com/qianlang/p/12573170.html
Copyright © 2011-2022 走看看