ASP.NET Core 2.0系列学习笔记-启动类Startup

Startup类可以用来定义处理管道和配置应用需要的服务。Startup类必须是public修饰,并且包含如下方法:

public class Startup
    {
        // 运行时调用此方法。使用此方法向容器添加服务。
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //使用此方法向容器添加服务。
        }

        // 运行时调用此方法。使用此方法配置HTTP请求管道。
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //使用此方法配置HTTP请求管道中间件。
        }
    }

ASP.NET Core 2.0 MVC 默认Startup类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace NETCoreMVC
{
    public class Startup
    {    //构造函数,加载配置文件
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; } //配置文件实体

        // 运行时调用此方法。使用此方法向容器添加服务。
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(); //添加MVC服务
        }

        // 运行时调用此方法。使用此方法配置HTTP请求管道。(Requsert请求管道)
        // 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.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

            //注册路由
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

}

总结:

1. ConfigureServices方法用于定义(注册)应用程序所使用的服务。(如:ASP.NET Core MVC,Entity Framework Core,Identity 等);

2. Configure方法用于定义请求管道的中间件,该管道将用于处理应用程序的所有请求。

3. 注册服务添加方法是无序的,ASP.NET Core在应用程序启动的时候,只要有相应服务即可,而注册中间件时方法是有序的,管道内的每一个组件都可以选择是否将请求交给下一个组件,并在管道中调用下一个组件之前或之后执行某些操作。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChaITSimpleLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值